기본 Django 관리 템플릿을 재정의하고 확장하는 방법은 무엇입니까?
확장하면서 동시에 관리 템플릿 (예 : admin / index.html)을 무시하는 방법 ( https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing 참조) -관리자 템플릿 )?
첫 번째-이 질문은 이전에 요청 및 답변되었음을 알고 있지만 ( Django : 앱 템플릿 재정의 및 확장 참조 ) app_directories 템플릿 로더 (대부분의 시각).
현재 해결 방법은 관리자 템플릿에서 직접 확장하는 대신 복사본을 만들어 확장하는 것입니다. 이것은 훌륭하지만 실제로는 혼란스럽고 관리자 템플릿이 변경되면 추가 작업을 추가합니다.
템플릿에 대한 사용자 지정 확장 태그를 생각할 수는 있지만 이미 솔루션이있는 경우 바퀴를 재발 명하고 싶지 않습니다.
참고로 : 장고 자체 가이 문제를 해결할지 아는 사람이 있습니까?
업데이트 :
사용중인 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 -템플릿
2011 년 원문 :
나는 약 1 년 반 전에 같은 문제가 있었고 djangosnippets.org 에서 멋진 템플릿 로더를 발견했습니다 . 특정 앱에서 템플릿을 확장 하여 관리 앱에서 admin / index.html 템플릿을 확장하는 고유 한 admin / index.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 %}
내 웹 사이트 의 블로그 게시물 에서이 템플릿 로더를 사용하는 방법에 대한 전체 예를 제공했습니다 .
Django 1.8이 현재 릴리스 인 경우 위의 답변에서 제안한대로 심볼릭 링크, 관리자 / 템플릿을 프로젝트 폴더에 복사하거나 미들웨어를 설치할 필요가 없습니다. 수행 할 작업은 다음과 같습니다.
다음과 같은 트리 구조를 만듭니다 ( 공식 문서에서 권장 )
your_project |-- your_project/ |-- myapp/ |-- templates/ |-- admin/ |-- myapp/ |-- change_form.html <- do not misspell this
참고 :이 파일의 위치는 중요하지 않습니다. 앱 안에 넣을 수 있으며 여전히 작동합니다. django가 위치를 찾을 수있는 한. 더 중요한 것은 HTML 파일의 이름이 django가 제공 한 원본 HTML 파일 이름과 같아야한다는 것입니다.
이 템플릿 경로를 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', ], }, }, ]
재 지정하려는 이름과 블록을 식별하십시오. django의 admin / templates 디렉토리를 살펴보면됩니다. virtualenv를 사용하고 있으므로 경로는 다음과 같습니다.
~/.virtualenvs/edge/lib/python2.7/site-packages/django/contrib/admin/templates/admin
이 예에서는 새 사용자 추가 양식을 수정하고 싶습니다. 이보기에 대한 템플리트 책임은 change_form.html 입니다. change_form.html을 열고 확장하려는 {% 블록 %}을 (를) 찾으십시오.
에서 당신의 change_form.html , 쓰기 일도이 맘에 :
{% extends "admin/change_form.html" %} {% block field_sets %} {# your modification here #} {% endblock %}
페이지를로드하면 변경 사항이 표시됩니다.
를 덮어 써야하는 경우 admin/index.html
의 index_template 매개 변수를 설정할 수 있습니다 AdminSite
.
예 :
# urls.py
...
from django.contrib import admin
admin.site.index_template = 'admin/my_custom_index.html'
admin.autodiscover()
템플릿을 <appname>/templates/admin/my_custom_index.html
으로 django
당신은 당신이 특정에 사용할 템플릿을 정의 할 수 있습니다 (적어도) 1.5modeladmin
https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#custom-template-options를 참조 하십시오
당신은 같은 것을 할 수 있습니다
class Myadmin(admin.ModelAdmin):
change_form_template = 'change_form.htm'
로 change_form.html
연장하는 간단한 HTML을 템플릿 인 admin/change_form.html
(또는하지 당신이 처음부터 작업을 수행하려는 경우)
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
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
I had to overwrite the login.html of the admin and therefore had to put the overwritten template in this folder structure:
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.
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:
templates/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.
I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.
Assuming the standard Django project structure:
mysite-container/ # project container directory
manage.py
mysite/ # project package
__init__.py
admin.py
apps.py
settings.py
urls.py
wsgi.py
app1/
app2/
...
static/
templates/
Here's what you need to do:
In
mysite/admin.py
, create a sub-class ofAdminSite
:from django.contrib.admin import AdminSite class CustomAdminSite(AdminSite): # set values for `site_header`, `site_title`, `index_title` etc. site_header = 'Custom Admin Site' ... # extend / override admin views, such as `index()` def index(self, request, extra_context=None): extra_context = extra_context or {} # do whatever you want to do and save the values in `extra_context` extra_context['world'] = 'Earth' return super(CustomAdminSite, self).index(request, extra_context) custom_admin_site = CustomAdminSite()
Make sure to import
custom_admin_site
in theadmin.py
of your apps and register your models on it to display them on your customized admin site (if you want to).In
mysite/apps.py
, create a sub-class ofAdminConfig
and setdefault_site
toadmin.CustomAdminSite
from the previous step:from django.contrib.admin.apps import AdminConfig class CustomAdminConfig(AdminConfig): default_site = 'admin.CustomAdminSite'
In
mysite/settings.py
, replacedjango.admin.site
inINSTALLED_APPS
withapps.CustomAdminConfig
(your custom admin app config from the previous step).In
mysite/urls.py
, replaceadmin.site.urls
from the admin URL tocustom_admin_site.urls
from .admin import custom_admin_site urlpatterns = [ ... path('admin/', custom_admin_site.urls), # for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)), ... ]
Create the template you want to modify in your
templates
directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifyingadmin/index.html
, create the filetemplates/admin/index.html
.All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.
Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.
For example, if you wanted to keep everything as-is but wanted to override the
content
block (which on the index page lists the apps and their models that you registered), add the following totemplates/admin/index.html
:{% extends 'admin/index.html' %} {% block content %} <h1> Hello, {{ world }}! </h1> {% endblock %}
To preserve the original contents of a block, add
{{ block.super }}
wherever you want the original contents to be displayed:{% extends 'admin/index.html' %} {% block content %} <h1> Hello, {{ world }}! </h1> {{ block.super }} {% endblock %}
You can also add custom styles and scripts by modifying the
extrastyle
andextrahead
blocks.
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:
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.
This site had a simple solution that worked with my Django 1.7 configuration.
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:
~/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:
{% 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.
Done. Easy.
You can use django-overextends, which provides circular template inheritance for Django.
It comes from the Mezzanine CMS, from where Stephen extracted it into a standalone Django extension.
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.
For deeper insides look at Stephens Blog "Circular Template Inheritance for 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.
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.
for app index add this line to somewhere common py file like url.py
admin.site.index_template = 'admin/custom_index.html'
for app module index : add this line to admin.py
admin.AdminSite.app_index_template = "servers/servers-home.html"
for change list : add this line to admin class:
change_list_template = "servers/servers_changelist.html"
for app module form template : add this line to your admin class
change_form_template = "servers/server_changeform.html"
etc. and find other in same admin's module classes
참고URL : https://stackoverflow.com/questions/6583877/how-to-override-and-extend-basic-django-admin-templates
'IT story' 카테고리의 다른 글
Spring MVC Controller에 대한 GET 요청에서 날짜 매개 변수를 수락하는 방법은 무엇입니까? (0) | 2020.07.27 |
---|---|
클래스에 함수가 정의되어 있는지 확인하는 가장 빠른 방법은 무엇입니까? (0) | 2020.07.27 |
ImportError : 이름이 bs4 인 모듈 없음 (BeautifulSoup) (0) | 2020.07.27 |
E : 리포지토리 'http://dl.google.com/linux/chrome/deb 안정 릴리스'에서 'Origin'값이 'Google, Inc.'에서 (0) | 2020.07.27 |
C / C ++에서 정규 분포에 따라 난수 생성 (0) | 2020.07.27 |