2016-07-14 66 views
1

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

需要注意的是:我沒有一個模型,這種形式

回答

0

感謝@丹尼爾羅斯曼,我弄明白了。

這裏是我改變了我的代碼:

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

你已經設置只有GET請求上的有效選項列表。在POST上,沒有選擇,所以該字段永遠不會有效。

該代碼應該在窗體的__init__方法中進行,因此每次窗體實例化時都會運行該代碼。

+0

好,謝謝你的建議,這是一個很好的起點! :)但是,我知道我應該有這樣的東西, def __init __(self,* args,** kwargs): super(DeleteDeviceForm,self).__ init __(* args,** kwargs) self.queryset = Device.objects.filter(user_id = ????) 我不知道我應該如何讓我的用戶ID在該窗體內......任何關於如何編碼的建議?非常感謝:) – Rose

+1

你需要從視圖中傳遞它,並從* args或** kwargs中獲取它。 –

相關問題