Admin ignores null=True in ForeignKey

1,223 views
Skip to first unread message

David Walker

unread,
Jan 10, 2011, 3:22:01 PM1/10/11
to django...@googlegroups.com
If I create a ForeignKey relationship between two Models with null=True, the Admin seems to still insist on there being a foreign object to link to.

For example, I created a very simple ForeignKey relationship from Things to Types:

from django.db import models

class Type(models.Model):
  name = models.CharField(max_length=30)
  
class Thing(models.Model):
  type_of_thing = models.ForeignKey(Type, null=True)
  name = models.CharField(max_length=30)

In the console, I can happily create Type-less Things:

>>> from ni.models import *
>>> x = Thing()
>>> x.name = 'Untyped thing'
>>> x.type = None
>>> x.save()
>>> all_things = Thing.objects.all()
>>> print all_things
[<Thing: Thing object>]
>>> print all_things[0].type_of_thing
None

In the Admin, however, when I try to add a new Thing, or even edit and save the existing Thing, the type_of_thing field is shown as required and saving without setting it causes "This field is required." to be displayed and the Thing not to be saved.

Am I doing something wrong?


Daniel Roseman

unread,
Jan 10, 2011, 5:49:00 PM1/10/11
to django...@googlegroups.com
Yes - you're not reading the documentation correctly. From http://docs.djangoproject.com/en/1.2/topics/db/models/#field-options :
Note that this [blank] is different than nullnull is purely database-related, whereas blank is validation-related. If a field has blank=True, validation on Django's admin site will allow entry of an empty value. If a field has blank=False, the field will be required.

So to allow empty entries in the admin, you need to use "blank=True, null=True". 
--
DR.
Reply all
Reply to author
Forward
0 new messages