django - 在 Django 的管理索引中显示每个模型的实例数

标签 django django-admin

我需要在主 django 站点管理页面上显示对象数量。
例如,在我需要显示的模型列表中

Elephants (6) 

代替
Elephants

我将此代码添加到我的模型中:
class Elephant(models.Model):
    ....
    class Meta:
        verbose_name_plural = 'Elephants ' + '(' + unicode(count_elephants()) + ')'

其中 count_elephants() 计算对象的数量。问题是verbose_name_plural 是在服务器启动时计算的,并且在我删除/插入对象时不会被调用,因此这个计算值变得无关紧要。
是否有可能以正确的方式做到这一点?
谢谢!

最佳答案

由于 verbose_name_plural 以许多其他方式使用,因此更好的方法是更改​​管理索引 View 和管理模板。

但是,由于管理应用程序可以更改,这可能与特定版本的
django。例如,我附上了从 django 1.2.5 获取的修改后的管理员。

(注意:我将使用原地替换 index 方法,但最好将其子类化而不是替换方法)

首先,从 django/contrib/admin/sites.py 复制 AdminSite.index 方法及其所需的导入,并将其修改为包含计数(更改了一行,查找“已添加此行”)。将其添加到任何您的 admin.py 文件或其他适当的地方:

from django.utils.text import capfirst
from django import template
from django.shortcuts import render_to_response
from django.views.decorators.cache import never_cache
from django.utils.translation import ugettext as _

def index_with_count(self, request, extra_context=None):
    """
    Displays the main admin index page, which lists all of the installed
    apps that have been registered in this site.
    """
    app_dict = {}
    user = request.user
    for model, model_admin in self._registry.items():
        app_label = model._meta.app_label
        has_module_perms = user.has_module_perms(app_label)

        if has_module_perms:
            perms = model_admin.get_model_perms(request)

            # Check whether user has any perm for this module.
            # If so, add the module to the model_list.
            if True in perms.values():
                model_dict = {
                    'name': capfirst(model._meta.verbose_name_plural),
                    'admin_url': mark_safe('%s/%s/' % (app_label, model.__name__.lower())),
                    'perms': perms,
                    'count': model.objects.count(), # THIS LINE WAS ADDED
                }
                if app_label in app_dict:
                    app_dict[app_label]['models'].append(model_dict)
                else:
                    app_dict[app_label] = {
                        'name': app_label.title(),
                        'app_url': app_label + '/',
                        'has_module_perms': has_module_perms,
                        'models': [model_dict],
                    }

    # Sort the apps alphabetically.
    app_list = app_dict.values()
    app_list.sort(lambda x, y: cmp(x['name'], y['name']))

    # Sort the models alphabetically within each app.
    for app in app_list:
        app['models'].sort(lambda x, y: cmp(x['name'], y['name']))

    context = {
        'title': _('Site administration'),
        'app_list': app_list,
        'root_path': self.root_path,
    }
    context.update(extra_context or {})
    context_instance = template.RequestContext(request, current_app=self.name)
    return render_to_response(self.index_template or 'admin/index.html', context,
        context_instance=context_instance
    )

site.index = never_cache(type(site.index)(index_with_count, site, AdminSite))

现在将 django/contrib/admin/templates/admin/index.html 文件复制到任何模板文件夹中的 admin/index.html 中,以覆盖原始模板并对其进行修改以显示计数:
{% extends "admin/base_site.html" %} 
{% load i18n %} 

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

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

{% block bodyclass %}dashboard{% endblock %} 

{% block breadcrumbs %}{% endblock %} 

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

{% if app_list %}
    {% for app in app_list %}
        <div class="module">
        <table summary="{% blocktrans with app.name as name %}Models available in the {{ name }} application.{% endblocktrans %}">
        <caption><a href="{{ app.app_url }}" class="section">{% blocktrans with app.name as name %}{{ name }}{% endblocktrans %}</a></caption>
        {% for model in app.models %}
            <tr>
              <th scope="row">
                {% if model.perms.change %}
                    <a href="{{ model.admin_url }}">{{ model.name }}</a>
                {% else %}
                    {{ model.name }}
                {% endif %}
                ({{ model.count }})
              </th>

            {% if model.perms.add %}
                <td><a href="{{ model.admin_url }}add/" class="addlink">{% trans 'Add' %}</a></td>
            {% else %}
                <td>&nbsp;</td>
            {% endif %}

            {% if model.perms.change %}
                <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 %}

{% block sidebar %}
<div id="content-related">
    <div class="module" id="recent-actions-module">
        <h2>{% trans 'Recent Actions' %}</h2>
        <h3>{% trans 'My Actions' %}</h3>
            {% load log %}
            {% get_admin_log 10 as admin_log for_user user %}
            {% if not admin_log %}
            <p>{% trans 'None available' %}</p>
            {% else %}
            <ul class="actionlist">
            {% for entry in admin_log %}
            <li class="{% if entry.is_addition %}addlink{% endif %}{% if entry.is_change %}changelink{% endif %}{% if entry.is_deletion %}deletelink{% endif %}">
                {% if entry.is_deletion %}
                    {{ entry.object_repr }}
                {% else %}
                    <a href="{{ entry.get_admin_url }}">{{ entry.object_repr }}</a>
                {% endif %}
                <br/>
                {% if entry.content_type %}
                    <span class="mini quiet">{% filter capfirst %}{% trans entry.content_type.name %}{% endfilter %}</span>
                {% else %}
                    <span class="mini quiet">{% trans 'Unknown content' %}</span>
                {% endif %}
            </li>
            {% endfor %}
            </ul>
            {% endif %}
    </div>
</div>
{% endblock %}

这会做到的。
(您仍然需要修改 app_index View 才能在应用索引页面中正确查看计数,我将其作为练习留给您 :-)

关于django - 在 Django 的管理索引中显示每个模型的实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241906/

相关文章:

php - 如何在我的 PHP-Apache-PostgreSQL 站点中嵌入 python 脚本?

django - Django 中的 "No ' 访问控制允许来源 ' header is present on the requested resource"

python - ManyToMany 字段上的 Django-admin 验证

python - Django 通过连接进行排序的效率 - 我可以强制使用子查询吗?

python - Django:列表显示管理中的外键值

django - 对于 django 管理员,如何向 User 模型添加字段并使其在管理员中可编辑?

python - Google Checkout 通知 API Python 示例

python - Django 聚合 : Sum return value only?

python - Django 管理员。显示分层下拉过滤器

python - django runscript 找不到脚本 'myscriptnamehere.py' 的(有效)模块