Created
December 20, 2010 05:09
-
-
Save bohde/748043 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class DependentCharField(models.CharField): | |
description = "A Field that can be null or blank if other returns a truthy value" | |
def __init__(self, dependentName, *args, **kwargs): | |
kwargs['blank'] = True | |
kwargs['null'] = True | |
self.dependentName = dependentName | |
return super(DependentCharField, self).__init__(*args, **kwargs) | |
def pre_save(self, model_instance, add): | |
otherValue = getattr(model_instance, self.dependentName, None) | |
thisValue = getattr(model_instance, self.attname, '') | |
if otherValue or thisValue: | |
return super(DependentCharField, self).pre_save(model_instance, add) | |
raise models.exceptions.ValidationError("%s can't be blank or null if %s is" % (self.attname, self.dependentName)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [2]: t = TestModel() | |
In [3]: t.save() | |
ValidationError: [u"test can't be blank or null if name is"] | |
In [4]: t = TestModel(name="foo") | |
In [5]: t.save() | |
In [6]: t = TestModel(test="bar") | |
In [7]: t.save() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from fields import DependentCharField | |
class TestModel(models.Model): | |
name = models.CharField(max_length=25) | |
test = DependentCharField('name', max_length=25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment