我正在 django 中创建一个表单,希望允许用户删除他们的一些设备。当我单击表单的提交按钮时,我不断收到消息:Select a valid choice. <Some choice> is not one of the available choices
. 这是我的代码。非常感谢 :)
表格.py
class DeleteDeviceForm(forms.Form):
devices = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
视图.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,})
请注意:我没有此表格的模型