0

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.

12
  • 1
    if you look at the doc ; dont use null for Charfield docs.djangoproject.com/en/dev/ref/models/fields/#null Commented Aug 19, 2013 at 15:11
  • This might be helpful: stackoverflow.com/questions/843580/… Commented Aug 19, 2013 at 15:12
  • Well, I'm prohibiting null but Django decides that when I give it None it should be converted to an empty string... Commented Aug 19, 2013 at 15:13
  • @mshsayem, it seems that user was trying to implement something different. Commented Aug 19, 2013 at 15:16
  • @youcha : so try blank=False , the validation should then failed. Commented Aug 19, 2013 at 15:17

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Do you mean the way to go is to override the save method to run full_clean before saving?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.