【问题标题】:Django admin add context to index.htmlDjango 管理员将上下文添加到 index.html
【发布时间】:2020-12-15 21:53:16
【问题描述】:

我正在尝试覆盖 Django 管理 index.html 以显示包含模型的最新 5 条记录的表

我设法在我的应用程序中使用以下内容覆盖了模板:

from django.contrib import admin

admin.site.index_template = 'admin/dashboard.html'
admin.autodiscover()

但我不知道如何将模型中的最新记录作为上下文添加到 index.html

希望有人可以帮助我

【问题讨论】:

    标签: python django django-templates django-admin django-context


    【解决方案1】:
    class CustomAdminSite(admin.AdminSite):
    
        def index(self, request, extra_context=None):
            extra_context = extra_context or {}
            # Add your context here
            return super(CustomAdminSite, self).index(request, extra_context)
    
    admin_site = CustomAdminSite()
    

    不要忘记将默认的admin 替换为admin_site

    【讨论】:

      【解决方案2】:

      对我添加额外上下文有用的东西是使用上下文处理器。在这里解释:https://stackoverflow.com/a/34903331/13436391

      Django documentation

      【讨论】:

        猜你喜欢
        • 2012-04-23
        • 1970-01-01
        • 2017-01-21
        • 2010-10-04
        • 2011-07-10
        • 2011-11-27
        • 2021-10-31
        • 2016-07-05
        • 1970-01-01
        相关资源
        最近更新 更多