I am creating a form in django, hoping to allow users to delete some of their devices. When I click on the submit button of my form, I keep getting the message: Select a valid choice. <Some choice> is not one of the available choices
. Here is my code. Thanks a lot :)
class DeleteDeviceForm(forms.Form):
devices = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
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,})
Note that: I don't have a model for this form
Thanks to @Daniel Roseman, I was able to figure it out.
Here is how I changed my code :
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)]
changed only one line to :
deletedeviceform = DeleteDeviceForm(request.POST, user=request.user.profile.pk)