django forms give: Select a valid choice. That choice is not one of the available choices

后端 未结 2 948
情话喂你
情话喂你 2021-02-02 15:50

I am unable to catch the values from the unit_id after the selection is done by the user and data is posted. Can someone help me to solve this.

The values o

相关标签:
2条回答
  • 2021-02-02 16:17

    Before you call form.is_valid(), do the following:

    1. unit_id = request.POST.get('unit_id')

    2. form.fields['unit_id'].choices = [(unit_id, unit_id)]

    Now you can call form.is_valid() and your form will validate correctly.

    0 讨论(0)
  • 2021-02-02 16:31

    You're getting a flat value_list back which will just be a list of the ids, but when you do that, you're probably better off using a plain ChoiceField instead of a ModelChoiceField and providing it with a list of tuples, not just ids. For example:

    class CommandSubmitForm(ModelForm):
        iquery = LiveDataFeed.objects.values_list('unit_id', flat=True).distinct()
        iquery_choices = [('', 'None')] + [(id, id) for id in iquery]
        unit_id = forms.ChoiceField(iquery_choices,
                                    required=False, widget=forms.Select())
    

    You could also leave it as a ModelChoiceField, and use LiveDataFeed.objects.all() as the queryset, but in order to display the id in the box as well as have it populate for the option values, you'd have to subclass ModelChoiceField to override the label_from_instance method. You can see an example in the docs here.

    0 讨论(0)
提交回复
热议问题