Django 프로젝트에 템플릿을 넣을 가장 좋은 위치는 어디입니까?
Django 프로젝트에 템플릿을 넣을 가장 좋은 위치는 어디입니까?
Django 책에서 4 장 :
템플릿을 넣을 명확한 위치를 생각할 수 없다면 Django 프로젝트 내에 템플릿 디렉토리를 생성하는 것이 좋습니다 (예를 들어 본 적이 있다면 2 장에서 만든 mysite 디렉토리 내에).
이것이 바로 제가하는 일이며 저에게 큰 도움이되었습니다.
내 디렉토리 구조는 다음과 같습니다.
/media
내 모든 CSS / JS / 이미지 등 의 기본 프로젝트 코드 (예 : Python 코드) 용
/templates
템플릿
/projectname
<PROJECT>/<APP>/templates/<APP>/template.html
앱을 다른 곳에서 재사용 할 수 있도록 도와주는 앱별 템플릿에 배치됩니다 .
일반적인 "글로벌"템플릿의 경우 <PROJECT>/templates/template.html
Dominic과 dlrust의 후속 조치는
우리는 django 프로젝트와 앱을 패키징하여 다양한 환경에 배포하기 위해 setuptools 소스 배포 (sdist)를 사용합니다.
템플릿과 정적 파일은 django 애플리케이션 디렉토리 아래에 있어야 setuptools로 패키징 할 수 있습니다.
예를 들어 템플릿과 정적 경로는 다음과 같습니다.
PROJECT/APP/templates/APP/template.html
PROJECT/APP/static/APP/my.js
이 기능이 작동하려면 MANIFEST.in을 수정해야합니다 ( http://docs.python.org/distutils/sourcedist.html#the-manifest-in-template 참조 ).
MANIFEST.in의 예 :
include setup.py
recursive-include PROJECT *.txt *.html *.js
recursive-include PROJECT *.css *.js *.png *.gif *.bmp *.ico *.jpg *.jpeg
또한 django 설정 파일에서 app_directories 로더가 TEMPLATE_LOADERS 에 있는지 확인해야합니다 . 기본적으로 django 1.4에 있다고 생각합니다.
django 설정 템플릿 로더의 예 :
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
rsync 파일을 처리하는 대신 sdists를 사용하는 이유가 궁금한 경우를 대비하여; 테스트, 승인 및 프로덕션 환경에 변경되지 않은 PIP로 배포되는 단일 빌드 타르볼이있는 구성 관리 워크 플로의 일부입니다.
DJANGO 1.11
기본 디렉토리 인 manage.py가있는 템플릿 폴더를 추가하십시오. settings.py에서 다음과 같이 TEMPLATES의 DIRS를 변경하십시오.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
],
},
},
]
이제 코드를 사용하여 템플릿을 사용하려면
def home(request):
return render(request,"index.html",{})
views.py에서. 이것은 django 1.11에서 완전히 잘 작동합니다.
나는 TEMPLATE_DIRS
절대 경로가 필요하다는 것을 이해했습니다 . 그리고 나는 내 코드에서 절대 경로를 좋아하지 않습니다. 그래서 이것은 나를 위해 잘 작동합니다 settings.py
.
import os
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(os.path.realpath(__file__)),
"../APPNAME/templates")
)
장고 1.10
TEMPLATE_DIRS
더 이상 사용되지 않습니다.
이제 우리는 사용에 필요 TEMPLATE
, 장고 1.8에서 도입 같이 :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
# ... some options here ...
},
},
]
Once you have defined TEMPLATES, you can safely remove ALLOWED_INCLUDE_ROOTS, TEMPLATE_CONTEXT_PROCESSORS, TEMPLATE_DEBUG, TEMPLATE_DIRS, TEMPLATE_LOADERS, and TEMPLATE_STRING_IF_INVALID.
About the best location, Django looking for template like this :
- DIRS defines a list of directories where the engine should look for template source files, in search order.
- APP_DIRS tells whether the engine should look for templates inside installed applications. Each backend defines a conventional name for the subdirectory inside applications where its templates should be stored.
More information : https://docs.djangoproject.com/en/1.10/topics/templates/#configuration
This is more a personal choice at the project-level. If you are talking about apps that need to be pluggable, then a templates directory in your app is the place where they go default. But project-wide, it is what works best for you.
Previous solution didn't work in my case. I used:
TEMPLATE_DIRS = [ os.path.join(os.path.dirname(os.path.realpath(__file__)),"../myapp/templates") ]
You could also consider having your templates in a database, using django-dbtemplates. It is also setup for caching, and the django-reversion application which helps you keep old versions of your templates around.
It works quite well, but I'd prefer a little more flexibility on the import/sync to/from filesystem side.
[edit: 20 Aug 2018 - this repository is no available, one with the same name is available at https://github.com/jazzband/django-dbtemplates and was updated 8 months ago. I no longer use Django in any meaningful way, so can't vouch for this.]
'programing tip' 카테고리의 다른 글
tinyhippos 주입 스크립트의 목적은 무엇입니까? (0) | 2020.09.25 |
---|---|
정말 좋고 나쁜 UTF-8 예제 테스트 데이터 (0) | 2020.09.25 |
Python : 생성기 표현식 대 수율 (0) | 2020.09.25 |
C # 스레드 종료 및 Thread.Abort () (0) | 2020.09.25 |
새로운 C # await 기능은 무엇을합니까? (0) | 2020.09.25 |