On Monday, January 10, 2011 8:22:01 PM UTC, David Walker wrote: > > 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? >
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 null<http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.Field.null> . null<http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.Field.null> is purely database-related, whereas blank<http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.Field.blank> is validation-related. If a field has blank=True<http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.Field.blank>, validation on Django's admin site will allow entry of an empty value. If a field has blank=False<http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.Field.blank>, the field will be required. So to allow empty entries in the admin, you need to use "blank=True, null=True". -- DR. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.