在Django的管理员索引中显示每个模型的实例数 [英] Display number of instances for each model in Django's admin index

查看:107
本文介绍了在Django的管理员索引中显示每个模型的实例数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 大象(6)

而不是

  Elephants 

我将此代码添加到我的模型中:

  class Elephant(models.Model):
....
class Meta:
verbose_name_plural ='Elephants'+'('+ unicode(count_elephants ())+')'

其中count_elephants()计算对象数。问题是在服务器启动时计算出verbose_name_plural,当我删除/插入对象时,不会调用verbose_name_plural,所以这个计算值就变得无关紧要了。
有可能以正确的方式做到吗?
谢谢!

解决方案

由于verbose_name_plural以许多其他方式使用,更好的方法是更改管理员索引视图和管理模板。



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



(注意:我将使用索引方法的替换,但它可能更好地子类化而不是替换方法)



作为开始,从django / contrib / admin / sites.py复制AdminSite.index方法,它需要导入,并将其修改为包括计数(一行更改,查找添加此行)将其添加到任何admin.py文件或其他适当的位置:



<$从django.utils.text导入capfirst
从django导入模板
从django.shortcuts导入render_to_response
从django.views.decorators.cache导入never_cache
from django.utils.translation import ugettext as _

def index_with_count(self,request,extra_context = None):

显示主要管理员索引页面,其中列出了已在本网站注册的所有已安装的
应用程序。

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)

如果has_module_perms:
perms = model_admin.get_model_perms(请求)

#检查用户是否
#如果是,将模块添加到model_list
如果在perms.values()中为True:
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(),#此行已添加
}
如果app_dict中的app_label:
app_dict [app_label] ['models']。 (model_dict)
else:
app_dict [app_label] = {
'name':app_label.title(),
'app_url':app_label +'/',
'has_module_perms':has_module_perms,
'models':[model_dict],
}

#按字母顺序排列应用程序。
app_list = app_dict.values()
app_list.sort(lambda x,y:cmp(x ['name'],y ['name'])

#在每个应用程序中按字母顺序排列模型。
在app_list中的
app ['models'] sort(lambda x,y:cmp(x ['name'],y ['name']))

context = {
'title':_('网站管理'),
'app_list':app_list,
'root_path':self.root_path,
}
context.update(extra_context或{})
context_instance = template.RequestContext(request,current_app = self.name)
返回render_to_response(self.index_template或'admin / index.html'
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中以覆盖原始模板并修改它以显示计数:

  {%extendsadmin / base_site.html%} 
{%load i18n%}

{%block extrastyle %} {{block.super}}< link rel =stylesheettype =text / csshref ={%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%}
{%app_list%中的应用程序}
< div class =module>
< table summary ={%blocktrans with app.name as name%}在{{name}}应用程序中可用的模型。{%endblocktrans%}>
< caption>< a href ={{app.app_url}}class =section> {%blocktrans with app.name as name%} {{name}} {%endblocktrans%} < / A>< /字幕>
{%for app.models%}
< tr>
< th范围=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'添加'%}< / a>< / td>
{%else%}
< td>& nbsp;< / td>
{%endif%}

{%if model.perms.change%}
< td>< a href ={{model.admin_url}} =changelink> {%trans'更改'%}< / a>< / td>
{%else%}
< td>& nbsp;< / td>
{%endif%}
< / tr>
{%endfor%}
< / table>
< / div>
{%endfor%}
{%else%}
< p> {%trans您没有权限编辑任何内容。 %}< / p为H.
{%endif%}
< / div>
{%endblock%}

{%block sidebar%}
< div id =content-related>
< div class =moduleid =recent-actions-module>
< h2> {%trans'最近动作'%}< / h2>
< h3> {%trans'我的操作'%}< / h3>
{%load log%}
{%get_admin_log 10作为admin_log for_user用户%}
{%如果不是admin_log%}
< p> {%trans'无可用 %}< / p为H.
{%else%}
< ul class =actionlist>
{%for 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%}< /跨度>
{%else%}
< span class =mini quiet> {%trans'未知内容'%}< / span>
{%endif%}
< / li>
{%endfor%}
< / ul>
{%endif%}
< / div>
< / div>
{%endblock%}

这样做。
(您仍然需要修改app_index视图才能在应用索引页面中正确查看计数,我将此作为您的一个练习: - )


I need to display number of objects at main django site admin page. For example, in list of models I need to display

Elephants (6) 

instead of

Elephants

I added this code to my model:

class Elephant(models.Model):
    ....
    class Meta:
        verbose_name_plural = 'Elephants ' + '(' + unicode(count_elephants()) + ')'

where count_elephants() calculates number of objects. The problem is that verbose_name_plural is calculated at server start and is not called when I delete/insert objects, so this calculated value becomes irrelevant. Is it possible to do it in correct way? Thanks!

解决方案

Since verbose_name_plural is used in many other ways, a better way to do this will be to change the admin index view and admin template.

However, since the admin app can change, this is probably tied to a specific version of django. I am attaching for example the modified admin taken from django 1.2.5.

(Note: I will use an in place replacement for the index method, but it will be probably better to subclass it instead of replacing the method)

As a start, copy from django/contrib/admin/sites.py the AdminSite.index method and it's required imports, and modify it to include counts (one line changed, look for 'THIS LINE WAS ADDED"). Add it to any of your admin.py files or somewhere else appropriate:

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))

Now copy the django/contrib/admin/templates/admin/index.html file into admin/index.html in any of your templates folders to override the original template and modify it to show the counts:

{% 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 %}

This will do it. (You will still need to modify the app_index view to see the counts correctly in the app index pages, I leave this as an exercise to you :-)

这篇关于在Django的管理员索引中显示每个模型的实例数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆