Non-nullable blank string-based model field validation doesn't prevent or clean `None`
|Reported by:||charettes||Owned by:||nobody|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
Description (last modified by charettes)
Since we discourage the use of NULLable string-based fields the assumed way of holding text that might be empty would be to use the blank option.
In this case I would expect full_clean to raise a ValidationError when an empty non-nullable field is assigned None:
from django.db import models class A(models.Model): b = models.CharField(blank=True) a = A(b=None) a.full_clean() # Passes a.save() # Integrity error
Unfortunately specifying blank=True disable all validation against the b field, leading to database integrity error upon calling save(). The obvious solution here would be to override A.clean to convert b to an empty string when it equals None but it strikes me as a non trivial change for a quite common use case: correctly allowing a string-based field to be empty.
This is not an issue when cleaning data retrieved from the usual application/form-url-encoded request.GET or request.POST since an empty value is always represented by the empty string. However, in the case of an application/json encoded payload one may either provide None or '' (null or '') to express emptiness. Which will trigger the issue described above.
Attaching a patch that special case the empty_values of non-nullable string based fields based on the empty_strings_allowed flag. All tests pass on Py2.7/SQLite3.
Change History (6)
comment:1 Changed 17 months ago by charettes
- Component changed from Uncategorized to Database layer (models, ORM)
- Has patch set