我正在django中创建一个表单,希望允许用户删除某些设备。当我单击表单的提交按钮时,我不断收到消息:Select a valid choice. <Some choice> is not one of the available choices
。这是我的代码。非常感谢 :)
表格
class DeleteDeviceForm(forms.Form):
devices = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
views.py
def delete_device(request):
if request.method == 'POST':
deletedeviceform = DeleteDeviceForm(request.POST)
if deletedeviceform.is_valid():
devicelist = request.POST.getlist('devices')
#will put other stuff there to process the data later, just want to access list now
return HttpResponseRedirect('/accounts/loggedin', {"devicelist": devicelist, })
else: #if not a POST request
userid = request.user.profile.pk
devices = Device.objects.filter(user_id=userid)
deletedeviceform = DeleteDeviceForm()
deletedeviceform.fields['devices'].choices = [(x.id, x) for x in devices]
return render(request, 'userprofile/delete_device.html', {"full_name": request.user.username, "deletedeviceform": deletedeviceform,})
请注意:我没有此表格的模型
最佳答案
您仅在GET请求中设置了有效选择的列表。在POST上,没有选择,因此该字段永远不会有效。
该代码应放在表单的__init__
方法中,因此每次实例化表单时都会运行该代码。