django many2many field make not required
I created a form based on a model. The model has a 开发者_Python百科many2many field. I defined the field like this:
contacts = models.ManyToManyField(Contact, blank=True, null=True)
I`m wondering now why the generated form says that this field cannot be blank. I always get the error message "This field is required.", when i do not select a contact for the contacts field.
Whats`s wrong?
In your form declaration mark this field as required=False
class MyForm(forms.ModelForm):
contacts=forms.ModelMultipleChoiceField(queryset=Contact.objects.all(),required=False)
class Meta:
model=MyModel
Possibly you did syncdb
before adding blank=True, null=True
?
syncdb
will only create tables if they don't exist in the database. Changes to models have to be done manually in the database directly with SQL or using a migration tool such as South.
Of course, if you are still in early development, it will be easier to drop the database and run syncdb
again.
Your use of null=True is confusing here. A manyToMany field results in a 3rd table relating one model to another. e.g.
Business <-> Contact
If business.contacts
is empty, no records are entered into this table. null=True
would make me think you are intending for NULL
records to be added to this table, which doesn't seem valid.
Typically you would leave both of these attributes off.
精彩评论