Reputation: 27
How to change my code so it would show all products in my View? Now it shows only these determined by filters.
Also how to make "neutral" option in filters so i can filter by only one category (in case of picking both 'neutrals' it will show all products).
Please see my code below:
> class ShopView(View):
> def get(self, request):
> order = request.GET.get('order', 'name')
> products, search_form = self.search_product(request)
> products = products.order_by(order)
> return render(request, 'shop.html', {'products':products, 'search_form':search_form})
>
> def search_product(self, request):
> search_form = FilterProductForm(request.GET)
> search_form.is_valid()
> shape = search_form.cleaned_data.get('shape')
> material = search_form.cleaned_data.get('material')
> queryset = Product.objects.all()
> filters = Q()
> if shape:
> filters.add(Q(shape__in=shape), Q.AND)
> if material:
> filters.add(Q(material__in=material), Q.OR)
> return queryset.filter(filters), search_form
and HTML: '''
{% block content %}
{% for product in products %}
<li>
<a href="{% url 'product_detail' product.id %}">
{{ product.name }}
</a>
</li>
{% endfor %}
<label>
<form>
{{ search_form.as_p }}
<input type="submit" value="Szukaj">
</form>
<a href="?order=price">Price ascending</a><br>
<a href="?order=-price">Price descending</a>
{% endblock %}
'''
Upvotes: 0
Views: 224
Reputation: 933
You will always have filtered queryset, because you are passing default parameter to the get
. Like here:
shape = search_form.cleaned_data.get('shape',[0,1,2])
material = search_form.cleaned_data.get('material',[0,1,2,3])
Do not provide default parameter(its None
by default):
shape = search_form.cleaned_data.get('shape')
material = search_form.cleaned_data.get('material')
Now, you have to check if there are filters provided. If not, simply return Product.objects.all()
queryset = Product.objects.all()
filters = Q()
if shape:
filters.add(Q(shape__in=shape), Q.AND)
if material:
filters.add(Q(material__in=material), Q.AND)
return queryset.filter(filters)
Upvotes: 1