Evgenii Legotckoi
Jan. 5, 2017, 6:47 p.m.

Django - Tutorial 016. Displays a list of popular articles on any page of the site

The site already had an article about the withdrawal the list of popular articles in the last 7 days . But in the variant that is used in this article shows how to draw a conclusion on the Articles page. But there was a question as to quickly implement a list of popular articles on any page of the site.

I have solved this problem by using its own tag , which can be used in a Django template. That is, instead of each View on the site to register the same code to obtain a list articles or the use of the same function in this View, I just did a single template with a finished layout for a list of popular articles, which uses my custom tag, which I take a list of these articles. Thus, you only need to implement this pattern in the right place in the page template using the include tag.


templatetags

As already mentioned, for the articles I used the knowledge module. In it, and create a custom tag. To do this, you need to create a folder templatetags and there two files: init .py, knowledge_extras.py.

Further, in the knowledge_extras.py writes a list of popular articles of the week.

# -*- coding: utf-8 -*-

from django import template
from django.db.models import Sum
from django.utils import timezone

from knowledge.models import ArticleStatistic

register = template.Library()


@register.simple_tag
def get_popular_articles_for_week():

    popular = ArticleStatistic.objects.filter(
        # filter records in the last 7 days
        date__range=[timezone.now() - timezone.timedelta(7), timezone.now()]
    ).values(
        # Taking the field of interest to us, namely, the id and the title
        # Unfortunately we can not to pick up an object on the foreign key in this case 
        # Only the specific field of the object
        'article_id', 'article__title', 'article__views',
    ).annotate(
        # Summing over rated recording
        sum_views=Sum('views')
    ).order_by(
        # sort the records Descending
        '-sum_views')[:5]    # Take 5 last records

    return popular

popular.html

Далее напишем шаблон, где будет применяться этот тег с вёрсткой списка популярных статей за неделю.

{% load knowledge_extras %}
{% get_popular_articles_for_week as POPULAR_ARTICLES %}
{% if POPULAR_ARTICLES %}
    {% load bootstrap3 %}
    <ul class="list-group">
        <li class="list-group-item active"><strong>Popular publications for the week</strong></li>
        {% for article in POPULAR_ARTICLES %}
            <li class="list-group-item">
                <a href="{% url 'post:article' article.article_id %}">{{ article.article__title }}</a>
            </li>
        {% endfor %}
    </ul>
{% endif %}

Using a template

In order to use this template, you just need to add it using the include tag is in place on the main page template, search templates, articles, or other template where you want to see the list of popular articles.

{% include 'knowledge/popular.html' %}

For Django I recommend VDS-server of Timeweb hoster .

Do you like it? Share on social networks!

АЗ
  • Jan. 25, 2017, 4:03 p.m.

Евгений, день добрый. За что в вашем конкретном примере отвечает __init__.py?

Evgenii Legotckoi
  • Jan. 25, 2017, 4:14 p.m.

Андрей, добрый день.
Данный файл отвечает за то, чтобы каталог templatetags и его содержимое рассматривались в качестве отдельного пакета. Это указание по разработке из официальной документации Django.

ИМ
  • Feb. 1, 2018, 4:59 a.m.

У меня только так заработало.

def get_popular_movies_for_week():

    popular = MovieStatistic.objects.filter(
        date__range=[timezone.now() - timezone.timedelta(7), timezone.now()]
    ).values(
        'movie_id', 'movie__name'
    ).annotate(
        views=Sum('views')
    ).order_by(
        '-views')[:5]

    return popular
Спасибо за статью.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html