gpt4 book ai didi

django 表单给出 : Select a valid choice. 该选项不是可用选项之一

转载 作者:行者123 更新时间:2023-12-03 20:27:58 25 4
gpt4 key购买 nike

我无法从 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))

最佳答案

你得到了一个平面 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 并为选项值填充它,您必须子类化 ModelChoiceField覆盖 label_from_instance方法。你可以看到一个 example in the docs here .

关于django 表单给出 : Select a valid choice. 该选项不是可用选项之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8536107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com