django表单给出:选择一个有效的选择。这种选择不是可用的选择之一

时间:2011-12-16 15:11:57

标签: django django-forms

在用户完成选择并发布数据后,我无法捕获unit_id中的值。有人可以帮我解决这个问题。

unit_id下拉列表的值是从另一个数据库表(LiveDataFeed)获取的。一旦选择了一个值并发布了表单,就会出现错误:

选择有效的选择。该选择不是可用的选择之一。

以下是实施:

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)  

在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 个答案:

答案 0 :(得分:12)

你得到一个平坦的value_list,它只是一个id列表,但是当你这样做时,你可能最好使用普通ChoiceField而不是ModelChoiceField和为它提供元组列表,而不仅仅是id。例如:

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

您也可以将其保留为ModelChoiceField,并使用LiveDataFeed.objects.all()作为查询集,但为了在框中显示ID以及为选项值填充,您可以d必须子类ModelChoiceField来覆盖label_from_instance方法。您可以看到example in the docs here

答案 1 :(得分:5)

在致电form.is_valid()之前,请执行以下操作:

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

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

  3. 现在您可以致电form.is_valid(),您的表单也会正确验证。

相关问题