django forms give: Select a valid choice. That cho

2020-05-21 05:10发布

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 of the unit_id drop down list is obtained from another database table (LiveDataFeed). And once a value is selected and form posted, it gives the error:

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

Here is the implementation:

in models.py:

class CommandData(models.Model):
    unit_id = models.CharField(max_length=50)
    command = models.CharField(max_length=50)
    communication_via = models.CharField(max_length=50)
    datetime = models.DateTimeField()
    status = models.CharField(max_length=50, choices=COMMAND_STATUS)  

In views.py:

class CommandSubmitForm(ModelForm):
    iquery = LiveDataFeed.objects.values_list('unit_id', flat=True).distinct()
    unit_id = forms.ModelChoiceField(queryset=iquery, empty_label='None',
        required=False, widget=forms.Select())

class Meta:
    model = CommandData
    fields = ('unit_id', 'command', 'communication_via')

def CommandSubmit(request):
    if request.method == 'POST':
        form = CommandSubmitForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponsRedirect('/')
    else:
        form = CommandSubmitForm()

    return render_to_response('command_send.html', {'form': form},
        context_instance=RequestContext(request))

2条回答
Ridiculous、
2楼-- · 2020-05-21 05:43

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.

查看更多
够拽才男人
3楼-- · 2020-05-21 05:53

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.

查看更多
登录 后发表回答