So I'm working on this Django e-commerce website where I'm supposed to filter the products on my page based on three separate categories. Since there were only three fixed categories, I decided to create a dictionary in my model class for Products and thought there would be a way to filter products later on in my templates accordingly using a {%For%} loop.
It's not working as I expected tho and I'm getting errors, probably because I'm not that familiar with Django and don't know how to get my way around it. Would greatly appreciate the help! (I've attached some screenshots for context)
working implementation of for loop that directly shows all products
CodePudding user response:
My recommendation is that you add an anchor tag
inside of the for loop
that will have the category name
which you can then pass as a keyword
to a defined url
for categories.
For example:
In the html
...
{% for product in products %}
...
# Adding this anchor tag to your existing code within the loop that will display each product's category.
# Also you can now send this category name to a specific view to filter the products
<a href="{% url 'category' product.category %}">{{ product.category|title }}</a>
# Notice that I have passed product.category as a keyword in {% url 'category' product.category %}
...
{% endfor %}
Now within your urls.py
file, just create a url to handle categories passed as keywords.
from .views import category_view # Importing the new view
urlpatterns = [
...
path('category/<str:category>/', category_view, name='category'),
...
]
From the views.py
file.
def category_view(request, category): # Accepting the category passed here
# You can have any other operations in here if necessary
products = Product.objects.filter(category__iexact=category)
context = {
...
'products': products,
...
}
return render(request, 'products.html', context)
That's the basic concept of what would solve your problem.
CodePudding user response:
I am using Class Based Views for the solutions. Basically you want to show the list of the products by category right. So the solution is as follows.
on views.py the view class is like this:
from django.views.generic import ListView
from .models import Product
class ProductListView(ListView):
model = Product
queryset = model.objects.all()
context_object_name = 'products'
template_name = 'your-template-path'
def get_queryset(self):
queryset = super(ProductListView, self).get_queryset()
category = self.request.GET.get('category', None)
if category:
return queryset.filter(category=category)
return queryset
Now send the category values on your URL parameter using category keyword. I am not using any authentication system. Please implement it on your own