我正在django中創建一個表單,希望允許用戶刪除他們的一些設備。當我點擊我的表單的提交按鈕時,我不斷收到消息:Select a valid choice. <Some choice> is not one of the available choices
。這是我的代碼。非常感謝:)MultipleChoiceField - invalid_choice錯誤 - 選擇一個有效的選項。 SomeChoice不是可用選項之一
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,})
需要注意的是:我沒有一個模型,這種形式
好,謝謝你的建議,這是一個很好的起點! :)但是,我知道我應該有這樣的東西, def __init __(self,* args,** kwargs): super(DeleteDeviceForm,self).__ init __(* args,** kwargs) self.queryset = Device.objects.filter(user_id = ????) 我不知道我應該如何讓我的用戶ID在該窗體內......任何關於如何編碼的建議?非常感謝:) – Rose
你需要從視圖中傳遞它,並從* args或** kwargs中獲取它。 –