views:

188

answers:

3

Hi,

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?

+1  A: 

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.

Van Gale
No I did run syncdb. I also did run django evolution http://code.google.com/p/django-evolution/. I thought also that this is the problem. Maybe a drop is a good idea.
Tom Tom
A: 

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.

robhudson
Ok but if i leave both of these attributes off, they are required. Actually it is not a big problem if the user has to add at least one m2m relationship, but it still would be interesting how this could be accomplished.
Tom Tom
+2  A: 

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
czarchaic
yes this works. thanks!
Tom Tom
do you know if I want to filter the contact with restriction that it should display only related to current instance of form, I mean it should display contacts related to Business not all. for new form should be empty, queryset=Contact.objects.filter(Contact.objects.filter(self.instance.????)
Tumbleweed