gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:50:12 25 4
gpt4 key购买 nike

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

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

最佳答案

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

关于python - MultipleChoiceField - invalid_choice 错误 - 选择有效选项。 SomeChoice 不是可用选项之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com