Should blank=True, default="" raise a "This field may not be null" validation error?

3,664 views
Skip to first unread message

Juan Antonio Alvarez

unread,
Aug 27, 2015, 8:14:47 PM8/27/15
to Django REST framework
If you set a model like so:

class Person(models.Model):
    nickname = models.CharField(max_length=50, blank=True, default="")
    (--- some more fields ---)

Then you include the 'nickname' field in the ModelSerializer.

When you send null to this field, you get a "This field may not be null" error. I know I can override the behaviour at a serializer level, but it seems to me that the serializer should accept the null value in this case, since the field has a default value.

What are your thoughts?

Tom Christie

unread,
Aug 28, 2015, 4:28:40 AM8/28/15
to Django REST framework
> it seems to me that the serializer should accept the null value in this case, since the field has a default value.

I'm pretty sure that happy with our current behavior here, which stands as:

* The field can be *omitted*, because it has a default value.
* Null is an invalid value, and will raise a validation error.

Chris Foresman

unread,
Aug 28, 2015, 10:13:36 AM8/28/15
to Django REST framework
You also have to consider that by standard practice, text and char fields shouldn't be nullable, because then you have two "non-value" values. By putting `null` for that field in the data sent to the serializer, you are saying explicitly to "set this field to `NULL`, but that's not possible because the field is `VARCHAR(50) NOT NULL`.

So, if the non-value for a field is a blank string, send that as the value. Or, as Tom noted, just omit the field in your input and then the default value is used by the serializer.
Reply all
Reply to author
Forward
0 new messages