L
L
Ladn02021-01-09 21:22:12
Django
Ladn0, 2021-01-09 21:22:12

How to automate template in django?

The bottom line is that I have a template for a news site, it has a list that lists all the categories of news in the form of blocks of 4 news for each category. So the question itself is how to transfer exactly 4 news from each category to these blocks, the presentation class for this template inherits the ListView class, I can submit a QuerySet with 4 news for each category separately by adding a line to the presentation class context[] = News.objects.filter(category_id=)[:5], but then when adding new category and, accordingly, news to it, you will have to manually add one more line to the view

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Ladn0, 2021-01-10
@Ladn0

In general, I did like this in Views.py

for i in range(1, Category.objects.count() + 1):    # Эта штука в принципе работает, но не до конца:(
            item3 = News.objects.filter(category_id=i)[:4]
            item2[Category.objects.get(pk=i)] = item3
            item1.append(item2)
            context['item2'] = item2
        return context

And in the template
{% for k, v in item2.items %}
{{ k }}
{% for i in v %}
{{ i.title }}
{% endfor %}
{% endfor %}

Thanks for the replies :3

R
Ranwise, 2021-01-09
@Ranwise

get all category ids and feed them most likely in a loop News.objects.filter(category_id=category_id)[:4]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question