如何覆盖和扩展基本的Django管理模板?

时间:2022-11-13 19:17:46

How do I override an admin template (e.g. admin/index.html) while at the same time extending it (see https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template)?

如何在重写管理模板(例如admin/index.html)的同时扩展它(参见https://docs.djangoproject.com/en/dev/ ref/adminb/# overriding-vs-replac-admin-template)?

First - I know that this question has been asked and answered before (see Django: Overriding AND extending an app template) but as the answer says it isn't directly applicable if you're using the app_directories template loader (which is most of the time).

首先——我知道这个问题以前已经被问过并回答过(参见Django:覆盖和扩展一个应用程序模板),但是正如答案所示,如果您使用app_directory模板加载器(大多数时候都是这样),那么这个问题并不直接适用。

My current workaround is to make copies and extend from them instead of extending directly from the admin templates. This works great but it's really confusing and adds extra work when the admin templates change.

我目前的解决方案是复制和扩展它们,而不是直接从管理模板扩展。这非常有效,但是当管理模板发生变化时,它会令人困惑,并增加额外的工作。

It could think of some custom extend-tag for the templates but I don't want to reinvent the wheel if there already exists a solution.

它可以为模板考虑一些自定义的扩展标记,但是如果已经存在解决方案,我不想重新创建*。

On a side note: Does anybody know if this problem will be addressed by Django itself?

顺便说一句:有人知道这个问题会不会被Django解决吗?

9 个解决方案

#1


80  

Update:

更新:

Read the Docs for your version of Django. e.g.

为您的Django版本阅读文档。如。

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#admin-overriding-templates https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#admin-overriding-templates

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/ admin-overriding-templates https://docs.djangoproject.com/en/2.0/ref/contrib/admin/ admin-overriding-templates

Original answer from 2011:

从2011年最初的回答:

I had the same issue about a year and a half ago and I found a nice template loader on djangosnippets.org that makes this easy. It allows you to extend a template in a specific app, giving you the ability to create your own admin/index.html that extends the admin/index.html template from the admin app. Like this:

大约一年半前,我遇到了同样的问题,我在djangosnippets.org上找到了一个很好的模板加载器,它使这一切变得很容易。它允许您在特定的应用程序中扩展模板,使您能够创建自己的管理/索引。扩展管理/索引的html。来自管理应用程序的html模板。

{% extends "admin:admin/index.html" %}

{% block sidebar %}
    {{block.super}}
    <div>
        <h1>Extra links</h1>
        <a href="/admin/extra/">My extra link</a>
    </div>
{% endblock %}

I've given a full example on how to use this template loader in a blog post on my website.

我已经在我的网站上的一篇博客文章中给出了如何使用这个模板加载器的完整示例。

#2


58  

As for Django 1.8 being the current release, there is no need to symlink, copy the admin/templates to your project folder, or install middlewares as suggested by the answers above. Here is what to do:

对于Django 1.8是当前的版本,不需要进行符号链接、将管理/模板复制到项目文件夹,或者按照上面的答案安装中间件。下面是要做的:

  1. create the following tree structure(recommended by the official documentation)

    创建以下树结构(由官方文档推荐)

    your_project
         |-- your_project/
         |-- myapp/
         |-- templates/
              |-- admin/
                  |-- myapp/
                      |-- change_form.html  <- do not misspell this
    

Note: The location of this file is not important. You can put it inside your app and it will still work. As long as its location can be discovered by django. What's more important is the name of the HTML file has to be the same as the original HTML file name provided by django.

注意:此文件的位置不重要。你可以把它放在你的应用里,它仍然可以工作。只要它的位置能被django发现。更重要的是HTML文件的名称必须与django提供的原始HTML文件名相同。

  1. Add this template path to your settings.py:

    将此模板路径添加到您的set .py:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')], # <- add this line
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
  2. Identify the name and block you want to override. This is done by looking into django's admin/templates directory. I am using virtualenv, so for me, the path is here:

    标识要覆盖的名称和块。这是通过查看django的管理/模板目录来实现的。我在使用virtualenv,对我来说,路径在这里:

    ~/.virtualenvs/edge/lib/python2.7/site-packages/django/contrib/admin/templates/admin
    

In this example, I want to modify the add new user form. The template responsiblve for this view is change_form.html. Open up the change_form.html and find the {% block %} that you want to extend.

在本例中,我想修改add new user表单。这个视图的模板响应是change_form.html。打开change_form。找到要扩展的{% block %}。

  1. In your change_form.html, write somethings like this:

    在你change_form。html,写这样的东西:

    {% extends "admin/change_form.html" %}
    {% block field_sets %}
         {# your modification here #}
    {% endblock %}
    
  2. Load up your page and you should see the changes

    加载您的页面,您将看到更改

#3


40  

if you need to overwrite the admin/index.html, you can set the index_template parameter of the AdminSite.

如果需要覆盖admin/index。html,可以设置AdminSite的index_template参数。

e.g.

如。

# urls.py
...
from django.contrib import admin

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

and place your template in <appname>/templates/admin/my_custom_index.html

并将模板放置在 /templates/admin/my_custom_index.html中

#4


11  

With django 1.5 (at least) you can define the template you want to use for a particular modeladmin

使用django 1.5(至少),您可以为特定的modeladmin定义您想要使用的模板。

see https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#custom-template-options

看到https://docs.djangoproject.com/en/1.5/ref/contrib/admin/ custom-template-options

You can do something like

你可以做一些类似的事情

class Myadmin(admin.ModelAdmin):
    change_form_template = 'change_form.htm'

With change_form.html being a simple html template extending admin/change_form.html (or not if you want to do it from scratch)

change_form。html是一个扩展admin/change_form的简单html模板。html(或者如果你想从头开始)

#5


5  

The best way to do it is to put the Django admin templates inside your project. So your templates would be in templates/admin while the stock Django admin templates would be in say template/django_admin. Then, you can do something like the following:

最好的方法是将Django管理模板放入您的项目中。因此,您的模板将在template/ admin中,而股票Django管理模板将在template/django_admin中。然后,你可以做如下的事情:

templates/admin/change_form.html

模板/ admin / change_form.html

{% extends 'django_admin/change_form.html' %}

Your stuff here

If you're worried about keeping the stock templates up to date, you can include them with svn externals or similar.

如果您担心使股票模板保持最新,您可以将它们包含在svn外部文件或类似文件中。

#6


4  

Chengs's answer is correct, howewer according to the admin docs not every admin template can be overwritten this way: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates

但是,根据管理文档,并不是每个管理模板都可以这样改写:https://docs.djangoproject.com/en/1.9/ref/admin/ #overriding-admin-templates。

Templates which may be overridden per app or model

每个应用程序或模型可以重写的模板

Not every template in contrib/admin/templates/admin may be overridden per app or per model. The following can:

不是每个应用程序或每个模型都可以覆盖悔过/管理/模板/管理中的每个模板。以下可能:

app_index.html
change_form.html
change_list.html
delete_confirmation.html
object_history.html

For those templates that cannot be overridden in this way, you may still override them for your entire project. Just place the new version in your templates/admin directory. This is particularly useful to create custom 404 and 500 pages

对于那些不能以这种方式被重写的模板,您可能仍然会为整个项目重写它们。只需将新版本放在模板/管理目录中。这对于创建自定义404和500页特别有用。

I had to overwrite the login.html of the admin and therefore had to put the overwritten template in this folder structure:

我必须覆盖登录名。html的管理员,因此必须把覆盖模板放在这个文件夹结构:

your_project
 |-- your_project/
 |-- myapp/
 |-- templates/
      |-- admin/
          |-- login.html  <- do not misspell this

(without the myapp subfolder in the admin) I do not have enough repution for commenting on Cheng's post this is why I had to write this as new answer.

(管理员中没有myapp子文件夹)我没有足够的权限评论Cheng的帖子这就是为什么我要写这个作为新的答案。

#7


1  

I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:

我同意克里斯·普拉特的观点。但是我认为最好是创建到原始Django文件夹的符号链接,在那里管理模板放置在:

ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin

and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.

您可以看到,它依赖于python版本和Django安装的文件夹。因此,在将来或生产服务器上,您可能需要更改路径。

#8


0  

This site had a simple solution that worked with my Django 1.7 configuration.

这个站点有一个简单的解决方案,它与我的Django 1.7配置一起工作。

FIRST: Make a symlink named admin_src in your project's template/ directory to your installed Django templates. For me on Dreamhost using a virtualenv, my "source" Django admin templates were in:

首先:在项目的模板/目录中创建一个名为admin_src的符号链接,并将其安装到Django模板中。对于使用virtualenv的Dreamhost,我的“源”Django管理模板在:

~/virtualenvs/mydomain/lib/python2.7/site-packages/django/contrib/admin/templates/admin

SECOND: Create an admin directory in templates/

第二:在模板/中创建一个管理目录。

So my project's template/ directory now looked like this:

我的项目模板/目录现在看起来是这样的:

/templates/
   admin
   admin_src -> [to django source]
   base.html
   index.html
   sitemap.xml
   etc...

THIRD: In your new template/admin/ directory create a base.html file with this content:

第三:在新的模板/管理/目录中创建一个基。包含以下内容的html文件:

{% extends "admin_src/base.html" %}

{% block extrahead %}
<link rel='shortcut icon' href='{{ STATIC_URL }}img/favicon-admin.ico' />
{% endblock %}

FOURTH: Add your admin favicon-admin.ico into your static root img folder.

第四:增加管理员权限。ico放入你的静态根img文件夹。

Done. Easy.

完成了。一件容易的事。

#9


0  

You can use django-overextends, which provides circular template inheritance for Django.

您可以使用Django - overextended,它为Django提供了循环模板继承。

It comes from the Mezzanine CMS, from where Stephen extracted it into a standalone Django extension.

它来自夹层CMS, Stephen将它提取到一个单独的Django扩展中。

More infos you find in "Overriding vs Extending Templates" (http:/mezzanine.jupo.org/docs/content-architecture.html#overriding-vs-extending-templates) inside the Mezzanine docs.

在Mezzanine文档中的“重写vs扩展模板”(http:/ mezzanine.org/docs/content -architecture.html# overriding-vsextending - Templates)中可以找到更多信息。

For deeper insides look at Stephens Blog "Circular Template Inheritance for Django" (http:/blog.jupo.org/2012/05/17/circular-template-inheritance-for-django).

要了解更多内幕,请查看Stephens的博客“Django的循环模板继承”(http:/blog.jupo.org/2012/05/17/ Circular - Template - Inheritance For Django)。

And in Google Groups the discussion (https:/groups.google.com/forum/#!topic/mezzanine-users/sUydcf_IZkQ) which started the development of this feature.

在谷歌组中,讨论(https:/groups.google.com/forum/#!topic/mezzanin -users/sUydcf_IZkQ)开始了这个特性的开发。

Note:

注意:

I don't have the reputation to add more than 2 links. But I think the links provide interesting background information. So I just left out a slash after "http(s):". Maybe someone with better reputation can repair the links and remove this note.

我没有添加超过两个链接的名声。但我认为这些链接提供了有趣的背景信息。所以我在"http(s):"后面省略了一个斜线。也许有信誉更好的人可以修复链接并删除这张纸条。

#1


80  

Update:

更新:

Read the Docs for your version of Django. e.g.

为您的Django版本阅读文档。如。

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#admin-overriding-templates https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#admin-overriding-templates

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/ admin-overriding-templates https://docs.djangoproject.com/en/2.0/ref/contrib/admin/ admin-overriding-templates

Original answer from 2011:

从2011年最初的回答:

I had the same issue about a year and a half ago and I found a nice template loader on djangosnippets.org that makes this easy. It allows you to extend a template in a specific app, giving you the ability to create your own admin/index.html that extends the admin/index.html template from the admin app. Like this:

大约一年半前,我遇到了同样的问题,我在djangosnippets.org上找到了一个很好的模板加载器,它使这一切变得很容易。它允许您在特定的应用程序中扩展模板,使您能够创建自己的管理/索引。扩展管理/索引的html。来自管理应用程序的html模板。

{% extends "admin:admin/index.html" %}

{% block sidebar %}
    {{block.super}}
    <div>
        <h1>Extra links</h1>
        <a href="/admin/extra/">My extra link</a>
    </div>
{% endblock %}

I've given a full example on how to use this template loader in a blog post on my website.

我已经在我的网站上的一篇博客文章中给出了如何使用这个模板加载器的完整示例。

#2


58  

As for Django 1.8 being the current release, there is no need to symlink, copy the admin/templates to your project folder, or install middlewares as suggested by the answers above. Here is what to do:

对于Django 1.8是当前的版本,不需要进行符号链接、将管理/模板复制到项目文件夹,或者按照上面的答案安装中间件。下面是要做的:

  1. create the following tree structure(recommended by the official documentation)

    创建以下树结构(由官方文档推荐)

    your_project
         |-- your_project/
         |-- myapp/
         |-- templates/
              |-- admin/
                  |-- myapp/
                      |-- change_form.html  <- do not misspell this
    

Note: The location of this file is not important. You can put it inside your app and it will still work. As long as its location can be discovered by django. What's more important is the name of the HTML file has to be the same as the original HTML file name provided by django.

注意:此文件的位置不重要。你可以把它放在你的应用里,它仍然可以工作。只要它的位置能被django发现。更重要的是HTML文件的名称必须与django提供的原始HTML文件名相同。

  1. Add this template path to your settings.py:

    将此模板路径添加到您的set .py:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')], # <- add this line
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
  2. Identify the name and block you want to override. This is done by looking into django's admin/templates directory. I am using virtualenv, so for me, the path is here:

    标识要覆盖的名称和块。这是通过查看django的管理/模板目录来实现的。我在使用virtualenv,对我来说,路径在这里:

    ~/.virtualenvs/edge/lib/python2.7/site-packages/django/contrib/admin/templates/admin
    

In this example, I want to modify the add new user form. The template responsiblve for this view is change_form.html. Open up the change_form.html and find the {% block %} that you want to extend.

在本例中,我想修改add new user表单。这个视图的模板响应是change_form.html。打开change_form。找到要扩展的{% block %}。

  1. In your change_form.html, write somethings like this:

    在你change_form。html,写这样的东西:

    {% extends "admin/change_form.html" %}
    {% block field_sets %}
         {# your modification here #}
    {% endblock %}
    
  2. Load up your page and you should see the changes

    加载您的页面,您将看到更改

#3


40  

if you need to overwrite the admin/index.html, you can set the index_template parameter of the AdminSite.

如果需要覆盖admin/index。html,可以设置AdminSite的index_template参数。

e.g.

如。

# urls.py
...
from django.contrib import admin

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

and place your template in <appname>/templates/admin/my_custom_index.html

并将模板放置在 /templates/admin/my_custom_index.html中

#4


11  

With django 1.5 (at least) you can define the template you want to use for a particular modeladmin

使用django 1.5(至少),您可以为特定的modeladmin定义您想要使用的模板。

see https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#custom-template-options

看到https://docs.djangoproject.com/en/1.5/ref/contrib/admin/ custom-template-options

You can do something like

你可以做一些类似的事情

class Myadmin(admin.ModelAdmin):
    change_form_template = 'change_form.htm'

With change_form.html being a simple html template extending admin/change_form.html (or not if you want to do it from scratch)

change_form。html是一个扩展admin/change_form的简单html模板。html(或者如果你想从头开始)

#5


5  

The best way to do it is to put the Django admin templates inside your project. So your templates would be in templates/admin while the stock Django admin templates would be in say template/django_admin. Then, you can do something like the following:

最好的方法是将Django管理模板放入您的项目中。因此,您的模板将在template/ admin中,而股票Django管理模板将在template/django_admin中。然后,你可以做如下的事情:

templates/admin/change_form.html

模板/ admin / change_form.html

{% extends 'django_admin/change_form.html' %}

Your stuff here

If you're worried about keeping the stock templates up to date, you can include them with svn externals or similar.

如果您担心使股票模板保持最新,您可以将它们包含在svn外部文件或类似文件中。

#6


4  

Chengs's answer is correct, howewer according to the admin docs not every admin template can be overwritten this way: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#overriding-admin-templates

但是,根据管理文档,并不是每个管理模板都可以这样改写:https://docs.djangoproject.com/en/1.9/ref/admin/ #overriding-admin-templates。

Templates which may be overridden per app or model

每个应用程序或模型可以重写的模板

Not every template in contrib/admin/templates/admin may be overridden per app or per model. The following can:

不是每个应用程序或每个模型都可以覆盖悔过/管理/模板/管理中的每个模板。以下可能:

app_index.html
change_form.html
change_list.html
delete_confirmation.html
object_history.html

For those templates that cannot be overridden in this way, you may still override them for your entire project. Just place the new version in your templates/admin directory. This is particularly useful to create custom 404 and 500 pages

对于那些不能以这种方式被重写的模板,您可能仍然会为整个项目重写它们。只需将新版本放在模板/管理目录中。这对于创建自定义404和500页特别有用。

I had to overwrite the login.html of the admin and therefore had to put the overwritten template in this folder structure:

我必须覆盖登录名。html的管理员,因此必须把覆盖模板放在这个文件夹结构:

your_project
 |-- your_project/
 |-- myapp/
 |-- templates/
      |-- admin/
          |-- login.html  <- do not misspell this

(without the myapp subfolder in the admin) I do not have enough repution for commenting on Cheng's post this is why I had to write this as new answer.

(管理员中没有myapp子文件夹)我没有足够的权限评论Cheng的帖子这就是为什么我要写这个作为新的答案。

#7


1  

I agree with Chris Pratt. But I think it's better to create the symlink to original Django folder where the admin templates place in:

我同意克里斯·普拉特的观点。但是我认为最好是创建到原始Django文件夹的符号链接,在那里管理模板放置在:

ln -s /usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/admin/ templates/django_admin

and as you can see it depends on python version and the folder where the Django installed. So in future or on a production server you might need to change the path.

您可以看到,它依赖于python版本和Django安装的文件夹。因此,在将来或生产服务器上,您可能需要更改路径。

#8


0  

This site had a simple solution that worked with my Django 1.7 configuration.

这个站点有一个简单的解决方案,它与我的Django 1.7配置一起工作。

FIRST: Make a symlink named admin_src in your project's template/ directory to your installed Django templates. For me on Dreamhost using a virtualenv, my "source" Django admin templates were in:

首先:在项目的模板/目录中创建一个名为admin_src的符号链接,并将其安装到Django模板中。对于使用virtualenv的Dreamhost,我的“源”Django管理模板在:

~/virtualenvs/mydomain/lib/python2.7/site-packages/django/contrib/admin/templates/admin

SECOND: Create an admin directory in templates/

第二:在模板/中创建一个管理目录。

So my project's template/ directory now looked like this:

我的项目模板/目录现在看起来是这样的:

/templates/
   admin
   admin_src -> [to django source]
   base.html
   index.html
   sitemap.xml
   etc...

THIRD: In your new template/admin/ directory create a base.html file with this content:

第三:在新的模板/管理/目录中创建一个基。包含以下内容的html文件:

{% extends "admin_src/base.html" %}

{% block extrahead %}
<link rel='shortcut icon' href='{{ STATIC_URL }}img/favicon-admin.ico' />
{% endblock %}

FOURTH: Add your admin favicon-admin.ico into your static root img folder.

第四:增加管理员权限。ico放入你的静态根img文件夹。

Done. Easy.

完成了。一件容易的事。

#9


0  

You can use django-overextends, which provides circular template inheritance for Django.

您可以使用Django - overextended,它为Django提供了循环模板继承。

It comes from the Mezzanine CMS, from where Stephen extracted it into a standalone Django extension.

它来自夹层CMS, Stephen将它提取到一个单独的Django扩展中。

More infos you find in "Overriding vs Extending Templates" (http:/mezzanine.jupo.org/docs/content-architecture.html#overriding-vs-extending-templates) inside the Mezzanine docs.

在Mezzanine文档中的“重写vs扩展模板”(http:/ mezzanine.org/docs/content -architecture.html# overriding-vsextending - Templates)中可以找到更多信息。

For deeper insides look at Stephens Blog "Circular Template Inheritance for Django" (http:/blog.jupo.org/2012/05/17/circular-template-inheritance-for-django).

要了解更多内幕,请查看Stephens的博客“Django的循环模板继承”(http:/blog.jupo.org/2012/05/17/ Circular - Template - Inheritance For Django)。

And in Google Groups the discussion (https:/groups.google.com/forum/#!topic/mezzanine-users/sUydcf_IZkQ) which started the development of this feature.

在谷歌组中,讨论(https:/groups.google.com/forum/#!topic/mezzanin -users/sUydcf_IZkQ)开始了这个特性的开发。

Note:

注意:

I don't have the reputation to add more than 2 links. But I think the links provide interesting background information. So I just left out a slash after "http(s):". Maybe someone with better reputation can repair the links and remove this note.

我没有添加超过两个链接的名声。但我认为这些链接提供了有趣的背景信息。所以我在"http(s):"后面省略了一个斜线。也许有信誉更好的人可以修复链接并删除这张纸条。