1

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

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

4

3 回答 3

2

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

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

于 2016-07-14T20:21:57.130 回答
2

感谢@Daniel Roseman,我能够弄清楚。

这是我更改代码的方式:

表格.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)]

视图.py

仅将一行更改为:

deletedeviceform = DeleteDeviceForm(request.POST, user=request.user.profile.pk)
于 2016-07-14T21:44:37.283 回答
0

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

pip install django-multiselectfield

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

于 2018-08-23T11:39:11.017 回答