Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is django admin not accepting Nullable foreign keys?

Here is a simplified version of one of my models:

class ImportRule(models.Model):
  feed = models.ForeignKey(Feed)
  name = models.CharField(max_length=255)
  feed_provider_category = models.ForeignKey(FeedProviderCategory, null=True)
  target_subcategories = models.ManyToManyField(Subcategory)

This class manages a rule for importing a list of items from a feed into the database.

The admin system won't let me add an ImportRule without selecting a feed_provider_category despite it being declared in the model as nullable. The database (SQLite at the moment) even checks out ok:

>>> .schema
...
CREATE TABLE "someapp_importrule" (
  "id" integer NOT NULL PRIMARY KEY,
  "feed_id" integer NOT NULL REFERENCES "someapp_feed" ("id"),
  "name" varchar(255) NOT NULL,
  "feed_provider_category_id" integer REFERENCES "someapp_feedprovidercategory" ("id"),
);
...

I can create the object in the python shell easily enough:

f = Feed.objects.get(pk=1)
i = ImportRule(name='test', feed=f)
i.save()

...but the admin system won't let me edit it, of course. How can I get the admin to let me edit/create objects without specifying that foreign key?

like image 815
p.g.l.hall Avatar asked Mar 22 '10 15:03

p.g.l.hall


People also ask

How do I allow null in ForeignKey Django?

Thus, if you want to make a field optional, use either default=SOMETHING, blank=True, null=False or blank=True, null=True . Another exception is the string-like field, such as CharField . It's suggested that use the blank=True alone, leaving null=False behind.

How do I restrict foreign keys choices to related objects only in Django?

Update: ForeignKey. limit_choices_to allows to specify either a constant, a callable or a Q object to restrict the allowable choices for the key.


1 Answers

How about blank=True? From Django's docs:

If True, the field is allowed to be blank. Default is False.

like image 50
jholster Avatar answered Sep 23 '22 22:09

jholster