How to connect my filter form to filter view Django?

Viewed 66

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>

enter image description here

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

1 Answers

You have to use to radio:

<form action="{% url 'filter' %}" method="get">
        <h2>Color:</h2>
        <input type="checkbox" name="colors []" id="" value="Red">Red<br>
        <input type="checkbox" name="colors []" id="" value="Blue">Blue<br>
        <h2>Material:</h2>
        <input type="checkbox" name="materials []" id="" value="Wood">Wood<br>
        <input type="checkbox" name="materials []" id="" value="Plastic">Plastic<br>
        <input type="checkbox" name="materials []" id="" value="Metal">Metal<br>
        <button type="submit">Find!</button>
    </form>

and in views.py:

colors ​​= self.request.POST.getlist ("colors []")
materials ​​= self.request.POST.getlist ("materials []")
Related