Wednesday, August 26, 2015

ForeignKey Fields null=True does not imply blank=True

Hi All,

I just discovered some interesting behaviour in Django 1.8.4 and was wondering if this was an unexpected side effect or specifically designed behaviour.


class UserProfile(models.Model):
    # Notice that I do not say that blank=True
    my_other_model = models.ForeignKey('my_app.OtherModel', null=True)


I would have expected that since it doesn't make sense for a ForeignKey to have a 'blank' value, by saying that null=True it would implicitly mean that blank=True.
However to my surprise this is not the case.

This came to my attention when using ModelForms. I found out that it is possible to assign the foreign key in the Form to a non null value, but it was not possible to reassign it back to the 'blank/null' value.

The reason is that in django/forms/models.py there is a function called '_get_validation_exclusions'. This function does a check on line 376

if not f.blank and not form_field.required and field_value in form_field.empty_values

which specifically looks at the 'blank' attribute of the model field. If this is False, then you will go into the if block and your field will be added to the exclusion list and therefore never saved.

To me, this seems like an unnecessary trap for users of the Django Framework. However there may be a design decision here and I'd love to be educated on why there would be a situation where it makes sense for null=True and blank=False.

Regards
Ben

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9a3dda01-eab8-4b53-8c24-5cb05414c2a1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment