访问Django Admin模板中的模型属性?

时间:2018-03-30 08:51:01

标签: python django django-templates django-admin

我在Python 3.5.3上有Django 2.0.3。我搜索简单的方法来改进我的标准Django Admin仪表板(Django Admin的主页)。

以下是管理主页./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 %}

我删除侧边栏,因为我从不使用它。它看起来像:

enter image description here

我想为每个模型添加对象的链接数。例如,Cities (23)Citizenships (102)和列表中的所有模型类似。我尝试在@property中使用./app/models.py装饰器添加功能,但它不起作用:

class APIConfig(models.Model):
    ...
    @property
    def with_active_status(self):
        return self.objects.filter(is_active=True).count()
    ...

我在管理员模板中调用此属性,例如{{ model.with_active_status }},但它没有显示任何内容。

1 个答案:

答案 0 :(得分:0)

这不是财产。您没有模型实例可以调用它。在任何情况下,如果你确实有一个实例它仍然无法工作,因为模型管理器 - objects - 只能从类而不是实例访问。

你应该把它变成一种类方法:

@classmethod
def with_active_status(cls):
    return cls.objects.filter(is_active=True).count()
相关问题