I have such html form on my page:
<form action="{% url 'filter' %}" method="get">
<h2>Color:</h2>
<input type="checkbox" name="red" id="">Red<br>
<input type="checkbox" name="blue" id="">Blue<br>
<h2>Material:</h2>
<input type="checkbox" name="wood" id="">Wood<br>
<input type="checkbox" name="plastic" id="">Plastic<br>
<input type="checkbox" name="metal" id="">Metal<br>
<button type="submit">Find!</button>
</form>
My Django model:
class Toy(models.Model):
COLORS = (
('Blue', 'Blue'),
('Red', 'Red')
)
MATERIALS = (
('Plastic', 'Plastic'),
('Wood', 'Wood'),
('Metal', 'Metal')
)
photo = models.ImageField(upload_to='images/', blank=True)
title = models.CharField(max_length=128, blank=False)
description = models.CharField(max_length=5000, blank=False)
price = models.PositiveIntegerField(blank=False)
count = models.PositiveIntegerField(blank=False)
color = models.CharField(max_length=128, blank=False, choices=COLORS)
material = models.CharField(max_length=128, blank=False, choices=MATERIALS)
and my view.py
def filter(request):
products = Toy.objects.all()
material = request.GET.get("material")
color = request.GET.get("color")
if material:
products = products.filter(material__in=material)
if color:
products = products.filter(color__in=color)
return render(request, 'catalog/products.html', {'products': products})
It should check my checkboxes and filter toys from a database that satisfied checked checkboxes
