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
})