How to get values of checked Checkboxes in Django form
In this lesson we will learn how to get values of all checked Checkboxes in Django form. It is really a simple task in Django.
How to get values of checked Checkboxes in Django form
Django has a method called
getlist
which returns data as a Python List. When you are using HTML checkboxes in a Django form you may have to collect multiple values from the checked checkboxes. Django’s getlist
method will help you in this case. You can access the value(s) of a specific named checkboxes like this:
0
1
2
|
request.POST.getlist('checkBoxName')
|
It is just that simple.
Here is an example regarding this. Assume that we have a Django form in which several boxes are available for choosing your speaking languages. It can be 1 or more than 1. In this case we will use Django’s
getlist
method.
0
1
2
3
4
5
|
<input type="checkbox" name="language" value="English" /> English
<input type="checkbox" name="language" value="Spanish" /> Spanish
<input type="checkbox" name="language" value="Mandarin" /> Mandarin
<input type="checkbox" name="language" value="Arabic" /> Arabic
|
To access the values from the checkboxes you can use
getlist
method like this:
0
1
2
|
language = request.POST.getlist('language')
|
Now the language variable contains Python list of language checkboxes. Then you can parse the values and use as you like. I hope, now you know how to get values of checked Checkboxes in Django form.