I have a form as below :
class CookDuty(forms.Form ):
# cook = None
def __init__(self, *args, **kwargs):
cook = kwargs.pop('cook')
super(CookDuty, self).__init__(*args, **kwargs)
self.fields['duty'].choices = foods_for_cook(cook)
duty = forms.ChoiceField(widget=forms.CheckboxSelectMultiple, required=False)
I have used it in a view as below, but form.is_valid
returns false! I have checked form.errors
and it's empty, form.data
is empty, and form.is_bound is False
.
def duty_list_cook(request):
if request.method == 'POST':
c = Cook.objects.all()[0]
form = CookDuty(cook=c)
if form.is_valid():
print(form.cleaned_data)
return render(request, 'employee/cook_duty.html', {'form':form})
else:
c = Cook.objects.all()[0]
form = CookDuty(cook=c)
return render (request, 'employee/cook_duty.html', {'form':form})
When it is a post request, you need to pass the POST data to the form.
if request.method == 'POST':
c = Cook.objects.all()[0]
form = CookDuty(cook=c, data=request.POST)
Without the post data, the form is unbound, so will always be invalid.
See the docs on bound and unbound forms for more info.
The second problem is that the ChoiceField
field (used for selecting a single choice) isn't compatible with the CheckboxSelectMultiple
widget (used for selecting multiple choices). If you want to select multiple choices, then you need to use MultipleChoiceField
instead of ChoiceField
.
duty = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, required=False)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments