MultipleChoiceField - invalid_choice 错误 - Select 一个有效的选择。 SomeChoice 不是可用选项之一

MultipleChoiceField - invalid_choice error - Select a valid choice. SomeChoice is not one of the available choices

我正在django中创建一个表单,希望允许用户删除他们的一些设备。当我单击表单的提交按钮时,我不断收到消息:Select a valid choice. <Some choice> is not one of the available choices。这是我的代码。非常感谢:)

forms.py

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__ 方法中,因此每次实例化表单时都是 运行。

多亏了@Daniel Roseman,我才弄明白了。

这是我更改代码的方式:

forms.py

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)]

views.py

仅将一行更改为:

deletedeviceform = DeleteDeviceForm(request.POST, user=request.user.profile.pk)

您可以使用非常简单的方法,您只需更新模型而不是表单。使用 django-multiselectfield

pip install django-multiselectfield

查看此处以供参考 https://pypi.org/project/django-multiselectfield/