Using of ModelMultipleChoiceField

Hello everyone, can you tell me where is the mistake I’ve made, is it impossible to use two model in a one model form? one is just a queryset. I am keep getting:
“Cannot assign “<QuerySet [<Cities: Naples>, <Cities: Istanbul>, <Cities: Wien>]>”: “State.city” must be a “Cities” instance.”

and my code is:

forms.py:

class StateForm(forms.ModelForm):
    city = forms.ModelMultipleChoiceField(queryset=Cities.objects.all(), required=True)
    class Meta:
        model = State
        fields = ('country','capital','city')
        widgets = {
            'country':forms.TextInput(attrs={"placeholder":"Country", "required":"True", "style":"width:40%;"}),
            'capital':forms.TextInput(attrs={"placeholder":"Capital", "required":"True", "style":"width:40%;"}),
            'city':forms.CheckboxSelectMultiple(attrs={"placeholder":"Choose a City"})
        }
        labels = {
            'country':'country',
            'capital':'capital',
            'city':'city',
        }

models.py:

class Cities(models.Model):
    city = models.CharField(max_length=100000)

    def __str__(self):
        return self.city

class State(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    country = models.CharField(max_length=100)
    capital = models.CharField(max_length=100)
    city = models.ForeignKey(Şehirler, on_delete = models.CASCADE)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.country)
        super(State, self).save(*args, **kwargs)

    def __str__(self):
        return self.country
    
    def get_absolute_url(self):
        return reverse('queryapp:details', args=[self.slug])

views.py:

def add_state(request):
    if request.method == 'POST':
        form = StateForm(data=request.POST)
        if form.is_valid():
            new_state = form.save(commit=False)
            new_state.user = request.user
            new_state.save()
            return redirect('http://127.0.0.1:8000/')
        else:
            print(form.errors)
    else:
        form = StateForm(data=request.GET)
    return render(request, 'queryapp/add_state.html',{
        'form':form
    })

In State model city is ForeignKey and In your StateForm you are trying ModelMultipleChoiceField which is used to assign Many to Many relation. In your case it should be ModelChoiceField to assign single object to city.
Cannot assign “<QuerySet [<Cities: Naples>, <Cities: Istanbul>, <Cities: Wien>]> this line stating that the result is QuerySet and city requires a single instance.

1 Like

oh OK then, there is no way to bind a queryset to a MultipleChoiceField right?

If your city field is required to store Many objects for single State instance then you can use models.ManyToManyField in your State model instead models.ForeignKey.
Else you have to use ModelChoiceField for models.ForeignKey.

1 Like

thank you for solving my problem

Note: If a City resides in one State, and each State can contain multiple cities, then your model is created incorrectly.

In a One-to-many relationship, the ForeignKey field is in the “Many” side of the relationship.

In this case, this means that City should have the FK to State, and not the reverse.

1 Like