TAGS :Viewed: 5 - Published at: a few seconds ago

[ Creating a model with null attribute. Bug in Django 1.3.6? ]

I start with this:

from django.db import models

class Example(models.Model):
     id = models.CharField(null=False, blank=False)
     name = models.CharField(null=False, blank=False)

Now if I create a new object with a name and without an id, the id will be replaced with an empty string and the object creation will be successful.

example = Example.objects.create(name="test")

I would like it to return an error instead since I specified null=False and blank=False. Is there a "native" way to do it? I'm using Django 1.3.6.

Answer 1

This is not a bug, of course, but is fully explained in the documentation. From the field options docs:

If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.

The key is the reference to validation. The docs also, naturally, have a whole selection on data validation. Again, from that page:

Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.

So, as the model validation page explains, to apply the validation for blank=False you should run the model's full_clean() method.

(In any case, there's no point in complaining about a possible bug in a version that's two releases old: if you think there is a bug, you should upgrade to the latest version and see if it has been fixed. Anyway, it's not a bug.)