Evgenij LegotskojMay 4, 2020, 2:21 p.m.

Django - Tutorial 053. Adding Counters to Models in the Django Admin Panel

Content

The other day, I started working on a content moderation application on the site and solved the problem of adding counters in the administrative panel.

It looks like this now

The task itself is trivial, but as it turned out there is a nuance, without knowing which, this task will not work right away.

Introduction

In order to set custom text for models in the administrative panel, we usually redefine the variable verbose_name_plural in the meta object of the model. The most common option is to add multilingual support. For example,

from django.utils.translation import ugettext_lazy as _

class Article(models.Model):

    class Meta:
        verbose_name = _('Article')
        verbose_name_plural = _('Articles')

It always works and we don’t think about why it works. And this works because ugettext_lazy is a lazy function that returns the result exactly when it is needed.

In the same way, you can return the number of objects or a specific number of objects and add them to this text in administrative ponel using lazy functions.

Example

In this way, for the moderation proxy model, I have drawn the number of unmoderated objects.

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

from django.utils.functional import lazy
from django.utils.translation import ugettext_lazy as _

from knowledge.models import Article
from moderation.managers import ArticleModeratedQuerySet


class ModeratedArticle(Article):

    class Meta:
        proxy = True
        verbose_name = _('Article')
        verbose_name_plural = lazy(lambda: _('Articles ({})').format(ModeratedArticle.objects.to_moderation().count()), str)()

    objects = ArticleModeratedQuerySet.as_manager()

Example description

Let's analyze the whole class. This is a special proxy model that

  • Allows you to display a model of articles in the moderation application
  • Which has a special object manager that will only return unmoderated objects

In fact, you are not interested in the object manager; it can release any logic that you plan to add to your application.
It is also not necessary that the model is a proxy model. All this you can do at your discretion.

But the most interesting line for you will be next

verbose_name_plural = lazy(lambda: _('Articles ({})').format(ModeratedArticle.objects.to_moderation().count()), str)()
  • Firstly, a lazy object is used here,
  • to which the function is transferred, it can be either a regular function or a lambda function. In my case, lambda.
  • a rotatable final data type is also passed str as the second argument lazy
  • and the function itself is executed to get the final instance, this is done using the parentheses operator at the end of the line ()

As a result, it will be possible to add a counter of objects of interest to the administrative panel.

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.
- company blog
Support the author Donate

Good

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
SG

C++ - Тест 003. Условия и циклы

  • Result:0points,
  • Rating points-10
a

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

  • Result:50points,
  • Rating points-4
M
  • Mili
  • Feb. 18, 2021, 9:22 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
t
  • t1m4
  • Feb. 24, 2021, 2:56 a.m.

Django - Tutorial 052. Redefining a User Model

В данном случае я заходил под superuser но все равно не появлялись эти поля

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Поднял сервис с помощью systemd, вот по этому мануалу: https://habr.com/ru/post/501414/
t
  • t1m4
  • Feb. 23, 2021, 7:11 a.m.

Django - Tutorial 052. Redefining a User Model

А как дать ему эти права?

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Всё по мануалу выше, буква в букву. gunicorn mysite.wsgi:application server { listen 80; server_name 10.0.3.15; access_log /var/log/nginx/example.log; locat…
Now discuss on the forum
M

нужна помощь с проектом qt c++

дали задание, на несколько дней. собираюсь делать, но хотел бы получить помощь более опытных людей, чтобы подкорректировать себя и подстраховаться. каким образом это можно сделать? …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.
Ds

При рендере тайлов появляется buffer reallocation

upd. с помощью double commander в сырцах OpenStreetMap плагина нашёл такую функцию size_t CoordBuffer::PushCoord(double x, double y) { if (usedPoints>=bufferSize) { buff…
GF

Сигналы и слоты в PyQt5

Решение стало следующим: после конвертации файла Ui из QtDesigner мне никак не выгодно продолжать работать в этом же файле, т.к. я постоянно продолжаю дорабатывать интерфейс, а его поведение я о…

Получение даты сборки программы

Проблему решил так: В .pro файле: VERSION = 1.2.3DEFINES += APP_VERSION=\\\"$$VERSION\\\"#Формирование даты и времени сборки (меняется при полной пересборке проекта)win32:{BLD_DATE=…
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB