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