我正在尝试将obj.html上复选框的动态选择发送到/ items函数。我遇到错误
"Select a valid choice. 1234 is not one of the available choices."
但是您会注意到,我从#views.py打印选项的查询集,它输出的1234包含在平面查询集中,并带有引号。
print(form.fields['choices'].queryset)
# Console output
['1234', '1243',...]
为什么1234不是可用的选择之一?我已经尝试在输入表单中的value属性周围加上引号,但是它不起作用。项目功能停止,因为数据无效。我该怎么解决?
# forms.py
class ItemForm(forms.Form):
choices = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple,
queryset = Sampledata.objects.none())
# views.py
def obj(request, object_id,):
data = Sampledata.objects.filter(id=object_id)
form = ItemForm()
form.fields['choices'].queryset = list(data.values_list('value', flat=True))
print(form.fields['choices'].queryset)
return render(request, 'obj.html', {'data':data,'form':form})
def items(request):
if request.method == 'POST':
form = ItemForm(request.POST)
# check whether it's valid:
if form.is_valid():
...
# obj.html
<form action="/items" method="post">
# Many of these spread out throughout the page
{% for obj in data %}
<input type="checkbox" name="choices" value="{{obj.value}}">
{% endfor %}
<input type="submit" value="Submit">
已更新,但仍然出现相同错误:
def items(request, object_id):
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ItemForm(request.POST)
data = Sampledata.objects.filter(id=object_id)
form.fields['choices'].queryset = (data.values_list('value', flat=True))
# check whether it's valid:
if form.is_valid():