ManyToManyField causes invalid form when limit_choices_to argument set

24 views
Skip to first unread message

rgreene

unread,
Apr 30, 2014, 3:50:11 PM4/30/14
to django...@googlegroups.com
Good day,

This is a somewhat contrived example, but I'm having the same problem in a real project.

Assuming continents have many countries, and countries can belong to many continents, I have a continent_country "junction" table in the database and am using ManyToManyField as follows...

Models:
class Country(models.Model):
    country_id = models.AutoField(primary_key=True)
    country_name = models.CharField(max_length=200)

    class Meta:
        managed = False
        db_table = 'country'

    def __unicode__(self):
        return '%s' % (self.country_name)

class Continent(models.Model):
    continent_id = models.AutoField(primary_key=True)
    continent_name = models.CharField(max_length=200)
    country = models.ManyToManyField(Country, db_table='continent_country', limit_choices_to=Q(country_id__exact=1))

    class Meta:
        managed = False
        db_table = 'continent'

Form:
class ContinentForm(ModelForm):
    class Meta:
        model = Continent
        widgets = {'country': CheckboxSelectMultiple}

Using this form, everything saves as expected if I remove the limit_choices_to=Q(country_id__exact=1)argument. However, using the form with the ManyToManyField configured as shown causes the form to be returned with is_valid=False in the POST, indicating that field country is required.

I traced into the django code for a bit, but as a relative rookie got somewhat lost! Why does limiting the list prevent django from setting the country? How to work around this? Any ideas greatly appreciated...

Thanks in advance,
Randal

rgreene

unread,
Apr 30, 2014, 4:06:35 PM4/30/14
to django...@googlegroups.com
Solved! It turned out the problem only occurred trying to uncheck the last checkbox. I needed to set blank=True on the ManyToManyField.
Reply all
Reply to author
Forward
0 new messages