Opened 5 years ago
Closed 5 years ago
#31072 closed Uncategorized (invalid)
Empty string validator not run on nullable charfield
Reported by: | thenewguy | Owned by: | nobody |
---|---|---|---|
Component: | Uncategorized | Version: | 3.0 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I need to store a CharField as null for unique together. I've hit an oddity attempting to prevent empty strings from passing validation.
I would expect for test_cannot_create_for_session_with_empty_string()
below to pass. It fails. However, test_cannot_create_altfoo_for_session_with_empty_string()
does pass.
def validate_truthy_or_null(value): if not value and value is not None: raise ValidationError('"%(value)s" was not truthy or null', params={'value': value}) class AbstractFoo(models.Model): class Meta: abstract = True session = models.CharField( max_length=255, null=True, blank=True, default=None, editable=False, validators=[validate_truthy_or_null], ) class Foo(AbstractFoo): pass class AltFoo(AbstractFoo) def clean(self): validate_truthy_or_null(self.session) class DemonstrationTests(TestCase): def test_validate_truthy_or_null(self): for value in ('', 0, False): with self.subTest(value=value): with self.assertRaises(ValidationError): validate_truthy_or_null(value) def test_cannot_create_for_session_with_empty_string(self): foo = Foo() foo.session = '' with self.assertRaises(ValidationError): foo.full_clean() def test_cannot_create_altfoo_for_session_with_empty_string(self): alt = AltFoo() alt.session = '' with self.assertRaises(ValidationError): alt.full_clean()
Note:
See TracTickets
for help on using tickets.
Closed. Looks like issue is editable=False per https://docs.djangoproject.com/en/3.0/ref/models/fields/#editable