django - 自定义 Django 管理索引页面以显示模型对象

标签 django templates django-models django-admin

在 Django 管理索引页面中,通常会列出应用程序及其模型。模型对象如何也列在此索引页中?我不想只显示应用程序,还想显示它的模型对象。应该如何定制?

enter image description here

最佳答案

我希望我的网站具有相同的功能,并通过对核心 django 系统进行轻微修改来添加它。

第一步:
首先,我们需要一种方法来指示哪些模型应该列出它们的属性。将以下代码添加到您想要列出实例的模型中(在 models.py 中):

class Meta:
    list_instances = True

第 2 步:
我们需要修改 Django 来识别和读取这个新属性。在核心 django 文件:db/models/options.py 中,大致在第 22 行将“list_instances”附加到 DEFAULT_NAMES:
DEFAULT_NAMES = ('verbose_name', 'verbose_name_plural', 'db_table', 'ordering',
             'unique_together', 'permissions', 'get_latest_by',
             'order_with_respect_to', 'app_label', 'db_tablespace',
             'abstract', 'managed', 'proxy', 'auto_created', 'list_instances')

在同一个文件中,大约在第 52 行,在其他属性之后为该属性创建一个默认字段:
self.list_instances = False

步骤 3 :
我们需要将此信息传递给生成索引页面的模板。在核心 django 文件:contrib/admin/sites.py 中,在 index() 方法和“if has_module_perms:”部分中,添加以下代码:
instances = []
if (model._meta.list_instances == True):
    instances = model_admin.queryset(None)

这将创建要显示的实例列表,但前提是设置了 list_instance 属性。在同一个文件中,再往下几行,将这些值附加到“model_dict”结构中。
model_dict = {
    'name': capfirst(model._meta.verbose_name_plural),
    'admin_url': mark_safe('%s/%s/' % (app_label, model.    __name__.lower())),
    'perms': perms,
    'list_instances':model._meta.list_instances,
    'instances': instances,
}

第 4 步 :
最后一步是修改模板以支持这一点。编辑 core-django 文件/contrib/admin/templates/admin/index.html 或将此文件复制到特定应用程序的 templates/admin/目录。如果适用,在用于生成行的标准代码之后添加几行以生成“子行”。大约在第 40 行,就在 "/tr>"和 "{% endfor %}"之间:
{% if model.list_instances %}
    {% for instance in model.instances %}
    <tr>
        <td colspan="2" style="padding-left: 2em;">{{ instance }}</td>
        {% if model.perms.change %}
            <td><a href="{{ model.admin_url }}{{ instance.id }}/" class="changelink">{% trans 'Change' %}</a></td>
        {% else %}
            <td>&nbsp;</td>
        {% endif %}
    </tr>
    {% endfor %}
{% endif %}

这将导致该项目以 生成的名称列出。 unicode () 方法在模型中。

步骤 5 :
瞧!它应该是这样的:

enter image description here

编辑:
可选步骤 6 :
如果您希望实例名称也可点击,只需更改模板 (index.html) 并替换:
<td colspan="2" style="padding-left: 2em;">{{ instance }}</td>

和:
<td colspan="2" style="padding-left: 2em;">        
    {% if model.perms.change %}            
        <a href="{{ model.admin_url }}{{ instance.id}}">{{ instance }}</a>
    {% else %}
        {{ instance }}
    {% endif %}
</td>

关于django - 自定义 Django 管理索引页面以显示模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7505006/

相关文章:

python - 如何在 Python 中用求和编写包含许多 AND 和 OR 的查询?

c++ - 如何检查所有可变参数模板参数是否具有特殊功能?

c++ - 如何使用 C++ 模板推断编译时 const char 字符串的大小?

python - 自定义 Django 用户模型 - 用户名作为主键属性

Django - 反向查询名称冲突

Django 模型保存创建者和修改者

python - Django 无法在 'default' 之外的其他数据库中创建 super 用户

javascript - Django "for"循环中的动态 Javascript 函数

Eclipse: "Simple"${word_selection} 的模板问题

Django - 网络商店模型组织