I'm new in django.
I has a django application where stores products categorized by 'X' and 'Y'.
views.py
...
class CartListView(ListView):
template_name = 'checkout/list.html'
context_object_name = 'product_list'
def get_queryset(self):
return Product.objects.filter(category__slug='X') | Product.objects.filter(category__slug='Y')
def get_context_data(self, **kwargs):
context = super(CartListView, self).get_context_data(**kwargs)
context['minicurso'] = get_object_or_404(Category, slug='X')
context['pacotes'] = get_object_or_404(Category, slug='Y')
return context
...
In my views.py I filter this products by your categories slug.
The problem is, I'm trying to render the products in category 'X' on top the page and the products in category 'Y' down with a text between them. How I can do this?
list.html
{% for category in product_list %}
{{ category.name }}
{% endfor %}
<p>
Any text
</p>
{% for category in product_list %}
{{ category.name }}
{% endfor %}
First off, you should use IN
operator over |
when populating the filtered queryset:
def get_queryset(self):
return Product.objects.filter(category__slug__in=["X", "Y"])
Secondly, you can't filter queryset by any field in the template unless you write a custom template tag which does that. However, it defeats the purpose of separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation. Thus, you need to override get_context_data
and pass each queryset into the context:
def get_context_data(self, **kwargs):
context = super(CartListView, self).get_context_data(**kwargs)
context['minicurso'] = get_object_or_404(Category, slug='X')
context['pacotes'] = get_object_or_404(Category, slug='Y')
context["x_product_list"] = self.get_queryset().filter(category=context['minicurso'])
context["y_product_list"] = self.get_queryset().filter(category=context['pacotes'])
return context
Then you can use them in the template:
{% for category in x_product_list %}
{{ category.name }}
{% endfor %}
...
{% for category in y_product_list %}
{{ category.name }}
{% endfor %}