Ihor
Ihor

Reputation: 117

Django filtering doesn't work with checkboxes

As far as i've understood my view doesn't get checked checkboxes. I can create 5 variables for 5 checkboxes but it seems to me wrong. I need to get all checked colors in variable 'color' and materials in 'material'. Then need to get all objects from database that satisfying these checked checkboxes

My form:

<form action="{% url 'filter' %}" method="POST">{% csrf_token %}
            <h2>Color:</h2>
            <input type="checkbox" name="red" id="" value="Red">Red<br>
            <input type="checkbox" name="blue" id="" value="Blue">Blue<br>
            <h2>Material:</h2>
            <input type="checkbox" name="wood" id="" value="Wood">Wood<br>
            <input type="checkbox" name="plastic" id="" value="Plastic">Plastic<br>
            <input type="checkbox" name="metal" id="" value="Metal">Metal<br>
            <button type="submit" value="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)

My views.py

def filter(request):
products = Toy.objects.all()

material = request.POST.get("what do i need to add here to find all products that satisfiying checked material checkboxes?")
color = request.POST.get("the same but with 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})

Upvotes: 0

Views: 196

Answers (1)

Art Vandelay
Art Vandelay

Reputation: 183

You should try using a Django Form: https://docs.djangoproject.com/en/3.2/topics/forms/#building-a-form

In combination with Django's Formview: https://docs.djangoproject.com/en/3.2/ref/class-based-views/generic-editing/#django.views.generic.edit.FormView

Your two form fields will be "color" and "material". Use a MultipleChoicefield (https://docs.djangoproject.com/en/3.2/ref/forms/fields/#multiplechoicefield).

Django will do most of the work for you with this setup.

Upvotes: 1

Related Questions