2

i have a ModelChoiceField that containts clients names selected from my database. but when submiting the form i get :

"Select a valid choice. That choice is not one of the available choices"

here is my form :

class FormVents(forms.Form):
  client_name=forms.ModelChoiceField(queryset=client.objects.all().values_list('nom', flat=True),required=False)

  def clean(self):
     client_name = self.cleaned_data.get('client_name')
     print(client_name)

i tryed to print client_name to check if i can get the value but i get None ! i guess that's why i always get that error Dont know what's the problem? is the way i call the field is not right ? any help please . Thank You so much

Elroum
  • 327
  • 1
  • 3
  • 18

1 Answers1

4

Remove .values_list('nom', flat=True).

IE

client_name=forms.ModelChoiceField(queryset=client.objects.all(), required=False)

If you want the value attribute to be a particular field from the model (the primary key is used by default), use the to_field_name keyword for the modelchoicefield.

For example,

client_name=forms.ModelChoiceField(queryset=client.objects.all(), to_field_name='nom', required=False)
sytech
  • 29,298
  • 3
  • 45
  • 86