Wednesday, April 30, 2014

ManyToManyField causes invalid form when limit_choices_to argument set

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/aa1249ca-dc1b-4abb-91e8-45a174a8506f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment