Opened 11 years ago

Last modified 3 years ago

#22224 closed Cleanup/optimization

Non-nullable blank string-based model field validation doesn't prevent or clean `None` — at Version 2

Reported by: Simon Charette Owned by: nobody
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Simon Charette)

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 (2)

comment:1 by Simon Charette, 11 years ago

Component: UncategorizedDatabase layer (models, ORM)
Has patch: set

comment:2 by Simon Charette, 11 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top