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 .
Евгений, день добрый. За что в вашем конкретном примере отвечает __init__.py?
Андрей, добрый день.
Данный файл отвечает за то, чтобы каталог templatetags и его содержимое рассматривались в качестве отдельного пакета. Это указание по разработке из официальной документации Django.
У меня только так заработало.