I would like to get multiple inputs from a checkboxes form something and then filter it out from my database. That would be something similar to:
http://127.0.0.1:8000/data/?class_type=[class_C,class_M]
However what I am receiving from the query is:
http://127.0.0.1:8000/data/?class_type=class_C&class_type=class_M
This is how it is coded, in .html:
Data class <br>
<div >
<input type="checkbox" value="class_C" id="class_C" name="class_type">
<label for="class_C">
C
</label>
</div>
<div >
<input type="checkbox" value="class_M" id="class_M" name="class_type">
<label for="class_M">
M
</label>
</div>
<div >
<input type="checkbox" value="class_X" id="class_X" name="class_type">
<label for="class_X">
X
</label>
</div>
In views.py:
data_class = request.GET.get('class_type')
[...]
if data_class == "class_C":
database = database.filter(class_l__contains = "C")
elif data_class == "class_M":
database = database.filter(class_l__contains = "M")
elif data_class == "class_X":
database = database.filter(class_l__contains = "X")
Any help is pretty appreciated! Thank you!
CodePudding user response:
You can obtain the list with .getlist(…)
[Django-doc]:
from django.db.models import Q
data_classes = request.GET.getlist('class_type')
acceptable_values = {'class_C', 'class_M', 'class_X'}
if all(data_class in acceptable_values for data_class in data_classes):
query = Q(*[Q(('class_l_contains', value)) for value in data_classes])
database = database.filter(query)
or for a logical OR:
from django.db.models import Q
data_classes = request.GET.getlist('class_type')
acceptable_values = {'class_C', 'class_M', 'class_X'}
if all(data_class in acceptable_values for data_class in data_classes):
query = Q(
*[Q(('class_l_contains', value)) for value in data_classes],
_connector=Q.OR
)
database = database.filter(query)