Evgenii Legotckoi
Evgenii LegotckoiJan. 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 .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

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
ДЛ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
СЦ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
AT

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
J
JonnyJoMarch 30, 2023, 11:57 a.m.
Qt/C++ - Lesson 021. The drawing mouse in Qt Евгений, здравствуйте! Только начал изучение Qt и возник вопрос по 21ому уроку. После написания кода, выдаёт следующие ошибки В чём может быть проблема?
АН
Алексей НиколаевMarch 26, 2023, 9:10 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
АН
Алексей НиколаевMarch 26, 2023, 9:04 a.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProject
NSProjectMarch 24, 2023, 2:35 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 10:09 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
Now discuss on the forum
BlinCT
BlinCTApril 1, 2023, 5:16 a.m.
Нужен совет по работе с ListView и несколькими моделями Спасибо, сейчас займусь этим.
NSProject
NSProjectMarch 31, 2023, 2:55 a.m.
Проверка комментария принадлежит он пользователю или нет DRF (Django Rest Framework) Здравствуйте! Сегодня я столкнулся с такой проблеммой. Существует модель комметариев. Где их соответственно достаточное количество. Все они выводятся при помощи запроса ajax (axios). Так ка…
P
PisychMarch 30, 2023, 2:50 a.m.
Как подсчитать количество по условию? Да! Вот так работает! Огромное Вам спасибо! ........
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
ВА
Виталий АнисимовJan. 29, 2023, 3:17 p.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.

Follow us in social networks