M
M
MalekBV2020-05-31 13:17:02
Django
MalekBV, 2020-05-31 13:17:02

django_filters. How to make a foreign key in the form of a set of Checkboxes?

I need to replace this view:
5hoFs.png

With this:
ZnIu9.png

Models

class Product(models.Model):
    """Store product"""
    category = models.ForeignKey(
        'Category',
        on_delete=models.SET_NULL,
        null=True,
        related_name='products'
    )

class Category(models.Model):
    """Product category"""
    name = models.CharField(max_length=50)


That is, the product has a foreign key to the category and I need to display all the categories in the form of checkboxes so that by selecting these categories I can find products that belong to them.

filters.py
class ProductFilter(django_filters.FilterSet):
    category = django_filters.ModelMultipleChoiceFilter(queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Product
        fields = ['category']


Views
class ProductFilterView(ListView):
    model = Product
    template_name = 'store/product-filter.html'
    context_object_name = 'products'

    def get_context_data(self, **kwargs):
    context['filter'] = ProductFilter(self.request.GET, queryset=self.get_queryset())


How can I filter products by category using checkboxes?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question