【问题标题】:Where is the Django Administration's view?Django 管理部门的观点在哪里?
【发布时间】:2015-11-13 07:09:16
【问题描述】:

我正在尝试修改原始的 Django 管理模板。我成功地添加了自定义内容。但是只有当我的数据库中的表为空时,我才需要显示此内容。因此,我想通过视图将一些内容传递给模板,但我找不到它。

更具体地说,我的扩展管理模板如下所示:

{% overextends "admin/index.html" %}
{% load i18n admin_urls %}

{% block content  %}
     {{ block.super }}

     {% if is_empty %}
         <a href="#">This hyperlink appears only when the table is empty</a>
     {% endif %}

{% endblock %}

我想将变量 is_empty 传递给模板是 True 还是 False,这取决于表是否为空。

有什么想法吗?

非常感谢!

【问题讨论】:

    标签: python django django-templates django-admin


    【解决方案1】:

    创建一个计算is_empty 值的template context processor

    # in my_app/context_processors.py
    from my_app.models import MyTable
    
    def is_empty(request):
        """Returns a bool depending on whether MyTable is empty"""
        return {'is_empty': not MyTable.objects.exists()} 
    

    将您的上下文处理器添加到您的模板设置中(请注意,对于 Django

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            ...
            'OPTIONS': {
                'context_processors': [
                    ...
                    'my_app.context_processors.is_empty',
                ],
            },
        },
    ]
    

    然后,您可以在使用请求上下文呈现的任何模板中包含 {{ is_empty }}。这包括管理视图、基于通用类的视图和使用render 快捷方式的视图。

    【讨论】:

    • 好的,我做到了:为了不出现异常,我必须做的唯一修复是做return {"is_empty": not MyTable.objects.exists()}。否则,绝对完美!谢谢!
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 2019-12-28
    相关资源
    最近更新 更多