P
P
PiggyPig2017-08-10 00:46:44
Django
PiggyPig, 2017-08-10 00:46:44

How to display an article only once?

In the template, you need to display a certain number of articles. But the problem is that articles can belong to several categories and with this conclusion

{% for article_page in article_pages %}
    ...
    {% for article in article_page.categories.all %}
        <a href="{% url 'articles' article.slug article_page.slug %}">
    {% endfor %}
    ...
{% endfor %}

we get one article, but with several different links. I don't need that happiness. Therefore, it is necessary to somehow display this article with any one category related to it in the link.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
PiggyPig, 2017-08-13
@PiggyPig

Finally found the answer. The above template element has been converted to this:

{% for article_page in article_pages %}
    ...
    <a href="{% url 'articles' article_page.categories.first.slug article_page.slug %}">
    ...
{% endfor %}

R
rorc, 2017-08-10
@rorc

It will be difficult to remove duplicates through the template engine here, if it is really necessary, then it is better to use processing at the views stage, removing duplicates or displaying articles through a template tag, in the code of which it is checked for matches.
An architectural error has already been made at the design stage of the url. {% url 'articles' article.slug article_page.slug %}. In any case, there will be duplicates, because. the url will be /cat1/article /cat2/article/
There are two ways to get rid of them:
1) Articles separately, categories separately. /url/catalog/name /url/article/name
In this case, even if the same article is displayed multiple times, the url is unique
2) One main category, url based on that category. The remaining categories are secondary, a separate list.
Why two nested loops were made is also not very clear, usually one loop and url based on querying data from a table by key.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question