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

时间:2016-07-14 18:48:12

标签: python django forms multiplechoicefield

我在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,})

请注意:我没有此表单的模型

3 个答案:

答案 0 :(得分:2)

您只在GET请求中设置了有效选项列表。在POST上,没有选择,因此该字段永远无效。

该代码应采用表单的__init__方法,因此每次实例化表单时都会运行该代码。

答案 1 :(得分:0)

感谢@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)

答案 2 :(得分:0)

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

pip install django-multiselectfield

在这里检查以供参考 https://pypi.org/project/django-multiselectfield/