Django not searching templates directory defined in APP_DIRS setings - python

I got a templates directory in same level as my project directory so I put in settings.py
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
but Django is not searching templates in apps it stops at DIRS
all apps needed are installed

My solution was to put the app name at the end of INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts' # <= put your app name here i guess?
]

I got this today (I'm on django 2.1). Solution was to add 'myappname' to the INSTALLED_APPS in settings (something you used to have to do on older django versions, but I thought was not mandatory anymore). Without doing this, django template processors were not looking to myappname/templates/myappname/
I also have the TEMPLATES_DIRS set up like some other answers, but for whatever reason that was not sufficient on my current setup (I broke my laptop, so I am django-ing on windows w brand new python 3.7 and brand new django 2.1 (didn't have to do this step the last time I worked w/ django about a week ago...)

Check your DIRS setting. It should include templates directory itself.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# True or False, depends on your case.
'APP_DIRS': True,
# Default django setup.
'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',
],
},
},
]

Just put the name of the template directory under the TEMPLATES array in the 'DIRS' section in your settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['your folder name'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'logyt_transporte.context_processors.module_variables',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

I was attempting to override templates from a third-party package.
My issue was that I had INSTALLED_APPS in the following order:
INSTALLED_APPS = [
# core
# third-party
# mine
]
Because I clearly glossed over the documentation which tells you this is not how it works: https://docs.djangoproject.com/en/3.1/ref/settings/#installed-apps
Specifically the last line:
When several applications provide different versions of the same
resource (template, static file, management command, translation), the
application listed first in INSTALLED_APPS has precedence.
Treat it like fallback order and ensure the overrides are before the originals, et voila. Sigh.

Related

Django 'DIRS': [] in settings.py TEMPLATES causes "TemplateDoesNotExist" Error

I'm using django version 2.1.2 with python 3.6.
I created two django projects (test01 & test02) by CMD.
Both of the projects are under the same folder.
Test01 executes normally, while test02 raises TemplateDoesNotExist error.
I've found a solution for the latter that is hard coding the address of templates in settings.py:
'DIRS': [r'C:\django\test02\accounts\templates']
However, another project can run normally even leaving this list as blank [].
The structures of both projects are the same:
Can anyone give a suggestion that can fix the problem in test02 without hard coding the address of templates in test02?
You may notice a built-in Django variable named BASE_DIR, it represents your root project, so you don't need to hard code the absolute path.
Add this in settings
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# codes...
],
},
},
]
Register all your apps, and Django will look for any files inside a folder named templates as you mentioned in os.path.join(BASE_DIR, 'templates')
Let create a folder called test01App in template and create base.html on it.
Then you can call test01App/base.html in response.
BACKEND is default of Django and you have to create folder templates.
You can customize where it stores template in other place in DIRS.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, './cuong')],
'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: flatpages/default.html not found when usign flatepages

I completed Django's 7 part tutorial and am now reading both the official documentation about flat pages as well as this other site.
in
my_project/settings.py
I have added the sites and flatpages apps as well as the SITE_ID.
in
my_project/urls.py
I have added
urlpatterns += [url(r'^pages/', include('django.contrib.flatpages.urls')),]
and because I also need to have flatpages/default.html as a template, in
my_project/templates/flatpages/
there is a file named default.html
to make sure it is found back in
my_projects/settings.py
I updated templates to look like:
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',
],
},
},
]
So I went onto the admin page and added a flatpage named "test" and then went to ...8000:/pages/test/
to get an error message TemplateDoesNotExist.
So where did I go wrong?
In order for your current DIRS in your TEMPLATES setting to work, make sure that your templates/flatpages/ directory is in your outer my_project directory (the one that contains manage.py), not the inner directory (the one that contains settings.py).

In password reset view custom templates not loading?

I am working on rest password via custum templates in django,but custom template not loading it is loading django's default template every time i load the /password_reset/ url.
I am using the url
url('^', include('django.contrib.auth.urls')),
i have a registration folder in templates and using this link to work
https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html
and the template folder is:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
],
'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',
"cms.utils.context_processors.permission_based_hidding_of_sidebar",
],
'libraries':{
'template_tag': 'cms.templatetags.template_tag',
'template_tag_time': 'cms.templatetags.tags',
}
},
},
]
install apps in settings:-
INSTALLED_APPS = [
'cms',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'django_csv_exports',
'django.contrib.auth',
'django.contrib.admin',
]
See my comment below. Sure, you can hack it and remove the form in the distribution library. Very very naughty. A much better solution is to alter the order in which the apps are loaded in your settings file. Originally I had:
INSTALLED_APPS = ['django.contrib.auth', 'ana_access',]
I just changed this so my app loaded first. And lo. That did it.
INSTALLED_APPS = ['ana_access','django.contrib.auth', ]
Conclusion: if you keep seeing the default page DESPITE having the form in your templates/registration folder, then it might be because you are loading the default django.contrib.auth app before your own.
Django 3.0. 2020. I solved the issue by adding template/registration/*.html in the project directory. This solved my issue. I don't need to change anything in the INSTALLED_APPS list.
Here are the steps:
Do the following highlighted changes in "settings.py"
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], # **ADD THIS
'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.template.context_processors.media',
'django.template.context_processors.static', # * (optional)
],
},
},
]
Create templates/registration directories in your project root folder and add your registration templates here instead of your_app/templates/registration.
Project_root_folder/templetes/registration/*.html
No need to change anything in INSTALLED_APPS of settings.py
If you want to override the Django admin template you need to created admin folder inside your templates directory. And place all your admin's files and folders there...
templates
|__ admin
|__ registration
Update: Also please correct the TEMPLATES DIR It should be
'DIRS': [os.path.join(BASE_DIR, 'templates')],

django override admin works locally not on production

I have the following directory structure in my django 10 project:
/my-project/ # project dir
+app1
+templates
+admin
base.html
404.html
500.html
My templates attribute looks like this in settings:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'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',
'common.context_processors.site_info',
],
},
},
]
My custom base.html displays on my local machine. When I upload this to my production server it no longer overrides and uses the base.html file in project folder.
I have changed around the order of apps suggested here and tried printing the dirs element of the templates attribute which prints "templates/" like here.
Does anyone know how I can get this to work on my production environment?
You must use absolute path in your settings to avoid issues. For example:
import os
PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..', '..')
# depending where your settings.py live
...
'DIRS': [
os.path.join(PROJECT_ROOT, 'templates'),
],

What is the path that Django uses for locating and loading templates?

I'm following this tutorial on a Windows 7 environment.
My settings file has this definition:
TEMPLATE_DIRS = (
'C:/django-project/myapp/mytemplates/admin'
)
I got the base_template from the template admin/base_site.html from within the default Django admin template directory in the source code of Django itself (django/contrib/admin/templates) into an admin subdirectory of myapp directory as the tutorial instructed, but it doesn't seem to take affect for some reason.
Any clue of what might be the problem?
I know this isn't in the Django tutorial, and shame on them, but it's better to set up relative paths for your path variables. You can set it up like so:
import os.path
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media/')
TEMPLATE_DIRS = [
os.path.join(PROJECT_PATH, 'templates/'),
]
This way you can move your Django project and your path roots will update automatically. This is useful when you're setting up your production server.
Second, there's something suspect to your TEMPLATE_DIRS path. It should point to the root of your template directory. Also, it should also end in a trailing /.
I'm just going to guess here that the .../admin/ directory is not your template root. If you still want to write absolute paths you should take out the reference to the admin template directory.
TEMPLATE_DIRS = [
'C:/django-project/myapp/mytemplates/',
]
With that being said, the template loaders by default should be set up to recursively traverse into your app directories to locate template files.
TEMPLATE_LOADERS = [
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
]
You shouldn't need to copy over the admin templates unless if you specifically want to overwrite something.
You will have to run a syncdb if you haven't run it yet. You'll also need to statically server your media files if you're hosting django through runserver.
If using Django settings as installed, then why not just use its baked-in, predefined BASE_DIR and TEMPLATES? In the pip installed Django(v1.8), I get:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
### ADD YOUR DIRECTORY HERE LIKE SO:
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',
],
},
},
]
Smart solution in Django 2.0.3 for keeping templates in project directory (/root/templates/app_name):
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMP_DIR],
...
in views.py just add such template path:
app_name/html_name
For Django 1.6.6:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = os.path.join(BASE_DIR, 'templates')
Also static and media for debug and production mode:
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
if DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
STATIC_ROOT = %REAL_PATH_TO_PRODUCTION_STATIC_FOLDER%
MEDIA_ROOT = %REAL_PATH_TO_PRODUCTION_MEDIA_FOLDER%
Into urls.py you must add:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from news.views import Index
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
...
)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
In Django 1.8 you can set template paths, backend and other parameters for templates in one dictionary (settings.py):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
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',
],
},
},
]
Official docs.
I also had issues with this part of the tutorial (used tutorial for version 1.7).
My mistake was that I only edited the 'Django administration' string, and did not pay enough attention to the manual.
This is the line from django/contrib/admin/templates/admin/base_site.html:
<h1 id="site-name">{{ site_header|default:_('Django administration') }}</h1>
But after some time and frustration it became clear that there was the 'site_header or default:_' statement, which should be removed. So after removing the statement (like the example in the manual everything worked like expected).
Example manual:
<h1 id="site-name">Polls Administration</h1>
Alright šŸ˜ Let's say you have a brand new project, if so you would go to settings.py file and search for TEMPLATES once you found it you just paste this line os.path.join(BASE_DIR, 'template') in 'DIRS' At the end, you should get somethings like this :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'template')
],
'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',
],
},
},
]
If you want to know where your BASE_DIR directory is located type these 3 simple commands:
python3 manage.py shell
Once you're in the shell :
>>> from django.conf import settings
>>> settings.BASE_DIR
PS: If you named your template folder with another name, you would change it here too.
In django 3.1, go to setting of your project and import os
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',
],
},
},
]
Contrary to some answers posted in this thread, adding 'DIRS': ['templates'] has no effect - it's redundant - since templates is the default path where Django looks for templates.
If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS in the main project settings.py.
INSTALLED_APPS': [
# ...
'my_app',
]
Quoting Django's Templates documentation:
class DjangoTemplatesĀ¶
Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.
When APP_DIRS is True, DjangoTemplates engines look for templates
in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.
When you create an application for your project, there's no templates directory inside the application directory. Django admin doesn't create the directory for you by default.
Below's another paragraph from Django Tutorial documentation, which is even clearer:
Your projectā€™s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a ā€œtemplatesā€ subdirectory in each of the INSTALLED_APPS.
In django 2.2 this is explained here
https://docs.djangoproject.com/en/2.2/howto/overriding-templates/
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
...,
'blog',
...,
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
basically BASE_DIR is your django project directory, same dir where manage.py is.
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',
],
},
},
]
By default django looks for the template folder in apps. But if you want to use template folder from root of project, please create a template folder on root of project and do the followings in settings.py:
import os
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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',
],
},
},
]
You can easily add template folder in settings.py folder, os.path is deprecated in django 3.1, so you can use path instead of os.path. You just have to import path in settings.py, you have to specify the base directory, then you have to specify template path, and last but not the least, you have to add template folder path in TEMPLATES = [{}], for example:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = Path(BASE_DIR, 'templates') (you can name TEMPLATE_DIR to any name)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'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',
],
},
},
]
One interesting thing I noted for templates searching
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
#'DIRS': [os.path.join(BASE_DIR,"templates")],
'DIRS': [],
'APP_DIRS': True,
if the app folder have templates sub-folder then only it is searched and listed under Template-loader postmortem
If app/templates do not exist, it is not listed in error messages. Understanding this will prevent newbee to add template folders via DIRS directive
This is for DJANGO version 4.x.x
To add templates folder open file settings.py and modify
'DIRS': [BASE_DIR / 'templates'],
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]

Categories

Resources