MohitC MohitC - 2 months ago 12
Python Question

Validate and get django form's unkown number of multipleselect checkbox fields

I am trying to get all selected checkboxes values as a list however not able to validate the form due to choices option

forms.py:

class MarkAccountsForm(forms.Form):
accounts = forms.MultipleChoiceField(
widget = forms.CheckboxSelectMultiple,
required = False
)


template:

{% for account in accounts %}
<tr>
<td><input type="checkbox" name="accounts" value="{{ account.id }}"></td>
<td>{{ account.name }}</td>
</tr>
{% endfor %}


views.py:

if request.method == 'POST':
form = MarkAccountsForm(request.POST)
if form.is_valid(): #this fails
data = form.cleaned_data


When I try to print
form.errors
, it says
Select a valid choice. 1119 is not one of the available choices.


Is there a way that I can avoid choice validation and still get values of all accounts checkboxes checked as a list? How do I say it to allow any for choices? If I can get the list without form validation then that is fine too.

Answer

If you don't care about validation, why are you calling is_valid? In fact, why are you using a Form class at all? You're not using it to display the form, so you might as well leave it out altogether and just get the data from request.POST.getlist('accounts').

Comments