V
V
Vic Shostak2018-03-31 13:15:46
Django
Vic Shostak, 2018-03-31 13:15:46

django admin. How to get the number of model objects in the master page template?

Good day!

I don’t really want to use third-party solutions that completely change the whole cool standard Django admin, so I’m looking for a way to customize it with the least change.

So, I have Django 2.0.3 on Python 3.5.3. There are several models, for example, these:
5abf57d0ac514248577338.png
At the output, I would like to get this look:
Cities (293)
Citizenships (504)
...

Where the number in brackets is the number of objects with a field is_active = Truefor this model.
Here is my admin home page template ( ./templates/admin/index.html ):
{% extends "admin/base_site.html" %}
{% load i18n static %}

{% block extrastyle %}{{ block.super }}
  <link rel="stylesheet" type="text/css" href="{% static "admin/css/dashboard.css" %}"/>{% endblock %}

{% block coltype %}colMS{% endblock %}

{% block bodyclass %}{{ block.super }} dashboard{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block content %}
  <div id="content-main">

    {% if app_list %}
      {% for app in app_list %}
        <div class="app-{{ app.app_label }} module">
          <table>
            <caption>
              <a href="{{ app.app_url }}" class="section"
                 title="{% blocktrans with name=app.name %}Models in the {{ name }} application{% endblocktrans %}">{{ app.name }}</a>
            </caption>
            {% for model in app.models %}
              <tr class="model-{{ model.object_name|lower }}">
                {% if model.admin_url %}
                  <th scope="row"><a href="{{ model.admin_url }}">{{ model.name }}</a></th>
                {% else %}
                  <th scope="row">{{ model.name }}</th>
                {% endif %}

                {% if model.add_url and request.user.is_superuser %}
                  <td><a href="{{ model.add_url }}" class="addlink">{% trans 'Add' %}</a></td>
                {% else %}
                  <td>&nbsp;</td>
                {% endif %}

                {% if model.admin_url and request.user.is_superuser %}
                  <td><a href="{{ model.admin_url }}" class="changelink">{% trans 'Change' %}</a></td>
                {% else %}
                  <td>&nbsp;</td>
                {% endif %}
              </tr>
            {% endfor %}
          </table>
        </div>
      {% endfor %}
    {% else %}
      <p>{% trans "You don't have permission to edit anything." %}</p>
    {% endif %}
  </div>
{% endblock %}

I will be glad to sensible comments.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-03-31
@vikkyshostak

Make a custom tag that will receive the model as an argument

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question