Reputation: 14783
I created a form based on a model. The model has a 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?
Upvotes: 1
Views: 1736
Reputation: 6328
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
Upvotes: 3
Reputation: 2658
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.
Upvotes: 0
Reputation: 43922
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.
Upvotes: 1