How to override and extend basic Django admin templates?

前端 未结 11 851
长发绾君心
长发绾君心 2020-11-22 14:11

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

11条回答
  •  无人及你
    2020-11-22 14:24

    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:

    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.

    1. Add this template path to your settings.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:

      ~/.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.

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

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

提交回复
热议问题