Reputation: 1043
Is it possible to write something like this in django templates:
{% for subcategory in category.subcategory.all %}
<li style="padding-left:20px">
<a href="/{{category.slug}}/{{subcategory.slug}}">
{{ subcategory.name }}
{{ sub_ + str(subcategory) }}
</a></li>
{% endfor %} <br>
In my views.py I have:
def index(request):
context = {}
categories = Category.objects.select_related()
subcategories = SubCategory.objects.all()
context['categories'] = categories
context['subcategories'] = subcategories
for subcategory in subcategories:
sites = Site.objects.filter(subcategory=subcategory, is_active=True)
print(sites.count())
context['sub_' + str(subcategory)] = sites.count()
print(context)
return render(request, 'mainapp/index.html', context)
I need to count Sites in each subcategory. I thought I can do it by making sub_category1, sub_category2 variables. But I don't know how can I get it in my template. Any ideas? When I write {{ sub_category1 }} it works. I need to put
Upvotes: 1
Views: 92
Reputation: 31260
{{ sub_ + str(subcategory) }}
No, this isn't going to work.
I would create a method on the SubCategory
model:
def get_active_sites(self):
return Site.objects.filter(subcategory=self, is_active=True)
Now you can use
{{ subcategory.get_active_sites.count }}
in the template. Similarly I'd replace /{{category.slug}}/{{subcategory.slug}}
with a method on SubCategory that uses reverse()
; probably named get_absolute_url()
.
Upvotes: 4