0

I already saw all question on Stackoverflow. But Still Not possible for me to solve this error. I want a dropdown list data to appear on my website. And that data I am getting from another model. So till here I am going good. Now When I try to save this data in database this error appear.

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

My Model is like this

 apn = models.CharField(null=True, blank=False, max_length=255)

My form.py file is like this

class labelModelForm(forms.ModelForm):
    class Meta:
        model = Labels_tool
      apn = forms.ModelChoiceField(queryset=Field.objects.values_list('sql_name', flat=True), empty_label="(Choose field)") 

And view.py file is :

 def ImportLabelView(self):
        self.form = labelModelForm(self.request.POST)
        # self.form = self.layer.form(self.request.POST)
        if self.save_form_if_appropriate('label'):
            return self.redirect('mapport.maps.layers.importlabel', self.map.id, self.layer.id)
        return self.render('mapport/maps/layers/Labels_detail.html')

Dropdown appearing on page is good . Just issue is when I try to save it in database.

[1]

ephemeral
  • 429
  • 2
  • 7
  • 16

1 Answers1

1

You shouldn't be using a values list. You should be using a normal queryset and then using to_field_name as shown here: https://docs.djangoproject.com/en/1.11/ref/forms/fields/#django.forms.ModelChoiceField.to_field_name.

apn = forms.ModelChoiceField(queryset=Field.objects.all(), empty_label="(Choose field)", to_field_name="sql_name")

Then when you go to save the things just extract the relevant information to save in apn, though really apn should just be a foreign key onto Field.

I would also consider looking at this question to see if it helps you: Change Django ModelChoiceField to show users' full names rather than usernames

I suspect that you are doing something in your database that you shouldn't really be doing.

Nick Chapman
  • 4,402
  • 1
  • 27
  • 41