我在django中创建一个表单,希望允许用户删除他们的一些设备。当我点击表单的提交按钮时,我会收到消息:Select a valid choice. <Some choice> is not one of the available choices
。这是我的代码。非常感谢:)
class DeleteDeviceForm(forms.Form):
devices = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
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,})
请注意:我没有此表单的模型
答案 0 :(得分:2)
您只在GET请求中设置了有效选项列表。在POST上,没有选择,因此该字段永远无效。
该代码应采用表单的__init__
方法,因此每次实例化表单时都会运行该代码。
答案 1 :(得分:0)
感谢@Daniel Roseman,我能够弄明白。
以下是我更改代码的方式:
class DeleteDeviceForm(forms.Form):
devices = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,label="Select the devices you want to delete:")
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(DeleteDeviceForm, self).__init__(*args, **kwargs)
self.fields['devices'].choices = [(x.id, x) for x in Device.objects.filter(user_id=user)]
只将一行更改为:
deletedeviceform = DeleteDeviceForm(request.POST, user=request.user.profile.pk)
答案 2 :(得分:0)
您可以使用非常简单的方法来更新模型而不是表格。使用django-multiselectfield
pip install django-multiselectfield