267π
First solution:
These settings
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
mean that Django will look at the templates from templates/
directory under your project.
Assuming your Django project is located at /usr/lib/python2.5/site-packages/projectname/
then with your settings django will look for the templates under /usr/lib/python2.5/site-packages/projectname/templates/
So in that case we want to move our templates to be structured like this:
/usr/lib/python2.5/site-packages/projectname/templates/template1.html
/usr/lib/python2.5/site-packages/projectname/templates/template2.html
/usr/lib/python2.5/site-packages/projectname/templates/template3.html
Second solution:
If that still doesnβt work and assuming that you have the apps configured in settings.py like this:
INSTALLED_APPS = (
'appname1',
'appname2',
'appname3',
)
By default Django will load the templates under templates/
directory under every installed apps. So with your directory structure, we want to move our templates to be like this:
/usr/lib/python2.5/site-packages/projectname/appname1/templates/template1.html
/usr/lib/python2.5/site-packages/projectname/appname2/templates/template2.html
/usr/lib/python2.5/site-packages/projectname/appname3/templates/template3.html
SETTINGS_PATH
may not be defined by default. In which case, you will want to define it (in settings.py):
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
92π
Find this tuple:
import os
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 need to add to βDIRSβ the string
os.path.join(BASE_DIR, 'templates')
So altogether you need:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(SETTINGS_PATH, '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',
],
},
},
]
- [Django]-How to completely dump the data for Django-CMS
- [Django]-Django queries β id vs pk
- [Django]-How do you configure Django to send mail through Postfix?
80π
If you encounter this problem when you add an app
from scratch. It is probably because that you miss some settings
. Three steps is needed when adding an app
.
1γCreate the directory and template file.
Suppose you have a project named mysite
and you want to add an app
named your_app_name
. Put your template file under mysite/your_app_name/templates/your_app_name
as following.
βββ mysite
βΒ Β βββ settings.py
βΒ Β βββ urls.py
βΒ Β βββ wsgi.py
βββ your_app_name
βΒ Β βββ admin.py
βΒ Β βββ apps.py
βΒ Β βββ models.py
βΒ Β βββ templates
βΒ Β βΒ Β βββ your_app_name
βΒ Β βΒ Β βββ my_index.html
βΒ Β βββ urls.py
βΒ Β βββ views.py
2γAdd your app
to INSTALLED_APPS
.
Modify settings.py
INSTALLED_APPS = [
...
'your_app_name',
...
]
3γAdd your app
directory to DIRS
in TEMPLATES
.
Modify settings.py
.
Add os import
import os
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'your_app_name', 'templates', 'your_app_name'),
...
]
}
]
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-Django annotation with nested filter
- [Django]-How to test Django's UpdateView?
15π
In setting .py remove TEMPLATE_LOADERS and TEMPLATE DIRS Then ADD
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/home/jay/apijay/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',
],
},
},
]
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Detect mobile, tablet or Desktop on Django
- [Django]-Django queries β id vs pk
11π
I had an embarrassing problemβ¦
I got this error because I was rushing and forgot to put the app in INSTALLED_APPS
. You would think Django would raise a more descriptive error.
- [Django]-Change a form value before validation in Django form
- [Django]-IOS app with Django
- [Django]-Sending post data from angularjs to django as JSON and not as raw content
8π
As of Django version tested on version 3
, You need to add your new app to installed app. No other code change is required for a django app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'addyourappnamehere'
]
- [Django]-Django south migration β Adding FULLTEXT indexes
- [Django]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
- [Django]-Pytest.mark.parametrize with django.test.SimpleTestCase
7π
May, 2023 Update:
templates
folder can be put just under django-project
folder or just under each app
folder as shown below:
django-project
|-core
βΒ |-settings.py
βΒ β-urls.py
|-app1
| |-urls.py
| β-views.py
|-app2
| |-urls.py
| β-views.py
β-templates # Here
|-app1
| β-a1.html
β-app2
β-a2.html
Or:
django-project
|-core
βΒ |-settings.py
βΒ β-urls.py
|-app1
| |-urls.py
| |-views.py
| β-templates # Here
| β-app1
| β-a1.html
β-app2
|-urls.py
|-views.py
β-templates # Here
β-app2
β-a2.html
For example first, you need set "app1"
and "app2"
to INSTALLED_APPS in settings.py
as shown below:
# "core/settings.py"
INSTALLED_APPS = [
...
"app1",
"app2",
]
Then if templates
folder is just under django-project
folder as shown below:
django-project
|-core
βΒ |-settings.py
βΒ β-urls.py
|-app1
| |-urls.py
| β-views.py
|-app2
| |-urls.py
| β-views.py
β-templates # Here
|-app1
| β-a1.html
β-app2
β-a2.html
Then, you need to set BASE_DIR / 'templates'
to "DIRS" in TEMPLATES in settings.py
as shown below. *I recommend to put templates
folder just under django-project
folder as shown above because you can easily manage templates in one place:
# "core/settings.py"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
BASE_DIR / 'templates' # Here
],
"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",
],
},
},
]
And, if templates
folder is just under each app
folder as shown below:
django-project
|-core
βΒ |-settings.py
βΒ β-urls.py
|-app1
| |-urls.py
| |-views.py
| β-templates # Here
| β-app1
| β-a1.html
β-app2
|-urls.py
|-views.py
β-templates # Here
β-app2
β-a2.html
Then, you need to keep "DIRS"
empty (which is default) without setting BASE_DIR / 'templates'
to "DIRS"
in TEMPLATES
in settings.py
as shown below:
# "core/settings.py"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [], # Keep it empty
"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",
],
},
},
]
Then, define test()
in app1/views.py
and app2/views.py
as shown below. Be careful, you need to set "app1/a1.html"
and "app2/a2.html"
instead of just setting "a1.html"
and "a2.html"
in render() as shown below:
# "app1/views.py"
from django.shortcuts import render
def test(request): # Don't set just "a1.html"
return render(request, "app1/a1.html")
# "app2/views.py"
from django.shortcuts import render
def test(request): # Don't set just "a2.html"
return render(request, "app2/a2.html")
Then, set each test
view of app1
and app2
in app1/urls.py
and app2/urls.py
as shown below:
# "app1/urls.py"
from django.urls import include, path
from . import views
app_name = "app1"
urlpatterns = [
path("", views.test, name='test'), # Here
]
# "app2/urls.py"
from django.urls import include, path
from . import views
app_name = "app2"
urlpatterns = [
path("", views.test, name='test'), # Here
]
Then, set each urls.py
of app1
and app2
in core/urls.py
as shown below, then the templates of app1
and app2
will be rendered without any errors:
# "core/urls.py"
from django.urls import include, path
urlpatterns = [
...
path("app1/", include('app1.urls')), # Here
path("app2/", include('app2.urls')) # Here
]
Lastly again, I recommend to put templates
folder just under django-project
folder as shown below because you can easily manage templates in one place:
django-project
|-core
βΒ |-settings.py
βΒ β-urls.py
|-app1
| |-urls.py
| β-views.py
|-app2
| |-urls.py
| β-views.py
β-templates # Here
|-app1
| β-a1.html
β-app2
β-a2.html
- [Django]-Django AutoField with primary_key vs default pk
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
- [Django]-How do you dynamically hide form fields in Django?
6π
For the django version 1.9,I added
'DIRS': [os.path.join(BASE_DIR, 'templates')],
line to the Templates block in settings.py
And it worked well
- [Django]-Itertools.groupby in a django template
- [Django]-How to check if a user is logged in (how to properly use user.is_authenticated)?
- [Django]-Django ignores router when running tests?
5π
Django TemplateDoesNotExist
error means simply that the framework canβt find the template file.
To use the template-loading API, youβll need to tell the framework where you store your templates. The place to do this is in your settings file (settings.py
) by TEMPLATE_DIRS
setting. By default itβs an empty tuple, so this setting tells Djangoβs template-loading mechanism where to look for templates.
Pick a directory where youβd like to store your templates and add it to TEMPLATE_DIRS e.g.:
TEMPLATE_DIRS = (
'/home/django/myproject/templates',
)
- [Django]-Django urlsafe base64 decoding with decryption
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-Django rest framework change primary key to use a unqiue field
4π
Just a hunch, but check out this article on Django template loading. In particular, make sure you have django.template.loaders.app_directories.Loader
in your TEMPLATE_LOADERS list.
- [Django]-Django storages: Import Error β no module named storages
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
- [Django]-Serving Media files during deployment in django 1.8
4π
Check permissions on templates and appname directories, either with ls -l or try doing an absolute path open() from django.
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-How do I filter query objects by date range in Django?
- [Django]-How to use pdb.set_trace() in a Django unittest?
4π
It works now after I tried
chown -R www-data:www-data /usr/lib/python2.5/site-packages/projectname/*
Itβs strange. I dont need to do this on the remote server to make it work.
Also, I have to run the following command on local machine to make all static files accessable but on remote server they are all βroot:rootβ.
chown -R www-data:www-data /var/www/projectname/*
Local machine runs on Ubuntu 8.04 desktop edition. Remote server is on Ubuntu 9.04 server edition.
Anybody knows why?
- [Django]-Django β {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Parsing unicode input using python json.loads
- [Django]-Why there are two process when i run python manage.py runserver
4π
Make sure youβve added your app to the project-name/app-namme/settings.py
INSTALLED_APPS: .
INSTALLED_APPS = ['app-name.apps.AppNameConfig']
And on project-name/app-namme/settings.py
TEMPLATES: .
'DIRS': [os.path.join(BASE_DIR, 'templates')],
- [Django]-How about having a SingletonModel in Django?
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-Celery : Execute task after a specific time gap
3π
I must use templates for a internal APP and it works for me:
'DIRS': [os.path.join(BASE_DIR + '/THE_APP_NAME', 'templates')],
- [Django]-How can I use the variables from "views.py" in JavasScript, "<script></script>" in a Django template?
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
- [Django]-How do I run tests against a Django data migration?
2π
add rest_framework
to the INSTALLED_APPS if django rest framework. For my case I had missed adding it to the installed apps.
INSTALLED_APPS = [
'..........',,
'rest_framework',
'.........',
]
- [Django]-How can i test for an empty queryset in Django?
- [Django]-Django middleware difference between process_request and process_view
- [Django]-How to force Django models to be released from memory
1π
See which folder django try to load template look at Template-loader postmortem
in error page, for example, error will sothing like this:
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.filesystem.Loader: d:\projects\vcsrc\vcsrc\templates\base.html (Source does not exist)
In my error vcsrc\vcsrc\templates\base.html
not in path.
Then change TEMPLATES
in setting.py
file to your templates path
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'vcsrc/templates')],
...
- [Django]-How to get the current URL within a Django template?
- [Django]-Django β {% csrf_token %} was used in a template, but the context did not provide the value
- [Django]-Complete django DB reset
1π
in your setting.py
file replace DIRS
in TEMPLATES
array with this
'DIRS': []
to this
'DIRS': [os.path.join(BASE_DIR, 'templates')],
but 1 think u need to know is that
you have to make a folder with name templates
and it should on the root path otherwise u have to change the DIRS
value
- [Django]-Add a custom button to a Django application's admin page
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
- [Django]-How to server HTTP/2 Protocol with django
1π
In my case it was enough just to include my application in INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
"myapp",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
Also, remember that the template should be placed in your directory like so:
myapp/templates/myapp/template_name.html
but when you point at this template you do this like that:
template = loader.get_template("myapp/template_name.html")
- [Django]-How can I filter a Django query with a list of values?
- [Django]-How to define two fields "unique" as couple
- [Django]-Trying to migrate in Django 1.9 β strange SQL error "django.db.utils.OperationalError: near ")": syntax error"
1π
django was configured to use templates in project_name/app_name/templates/app_name/template.html when referred with render(request, βapp_name/template.htmlβ, context)
If you got Template exception the reason is that you hadnβt add app_name to installed_apps in settings.
I had the issue with django 4.1
- [Django]-Handling race condition in model.save()
- [Django]-How to run celery as a daemon in production?
- [Django]-How to check if ManyToMany field is not empty?
0π
Check that your templates.html are in /usr/lib/python2.5/site-packages/projectname/templates
dir.
- [Django]-Gunicorn Connection in Use: ('0.0.0.0', 5000)
- [Django]-Resource temporarily unavailable using uwsgi + nginx
- [Django]-Django character set with MySQL weirdness
0π
Hi guys I found a new solution. Actually it is defined in another template so instead of defining TEMPLATE_DIRS yourself, put your directory path name at their:
- [Django]-Django.contrib.auth.logout in Django
- [Django]-Images from ImageField in Django don't load in template
- [Django]-Creating a JSON response using Django and Python
0π
Iβm embarrassed to admit this, but the problem for me was that a template had been specified as β¦.hml
instead of β¦.html
. Watch out!
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
- [Django]-How can I keep test data after Django tests complete?
- [Django]-Is there a list of Pytz Timezones?
0π
I added this
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
and it still showed the error, then I realized that in another project the templates was showing without adding that code in settings.py file so I checked that project and I realized that I didnβt create a virtual environment in this project so I did
virtualenv env
and it worked, donβt know why
- [Django]-Django limit_choices_to for multiple fields with "or" condition
- [Django]-Are Django SECRET_KEY's per instance or per app?
- [Django]-Django Multiple Authentication Backend for one project
0π
I came up with this problem. Here is how I solved this:
Look at your settings.py, locate to TEMPLATES
variable,
inside the TEMPLATES, add your templates path inside the DIRS
list. For me, first I set my templates path as TEMPLATES_PATH = os.path.join(BASE_DIR,'templates')
, then add TEMPLATES_PATH
into DIRS
list, 'DIRS':[TEMPLATES_PATH,]
.
Then restart the server, the TemplateDoesNotExist exception is gone.
Thatβs it.
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
- [Django]-How to get GET request values in Django?
0π
1.create a folder βtemplatesβ in your βapp'(let say you named such your app)
and you can put the html file here.
But it s strongly recommended to create a folder with same name(βappβ) in βtemplatesβ folder and only then put htmls there. Into the βapp/templates/appβ folder
2.now in βappβ βs urls.py put:
path('', views.index, name='index'), # in case of use default server index.html
3. in βappβ βs views.py put:
from django.shortcuts import render
def index(request): return
render(request,"app/index.html")
# name 'index' as you want
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
- [Django]-Django, Models & Forms: replace "This field is required" message
- [Django]-'staticfiles' is not a valid tag library: Template library staticfiles not found
0π
Works on Django 3
I found I believe good way, I have the base.html in root folder, and all other html files in App folders, I
settings.py
import os
# This settings are to allow store templates,static and media files in root folder
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# This is default path from Django, must be added
#AFTER our BASE_DIR otherwise DB will be broken.
BASE_DIR = Path(__file__).resolve().parent.parent
# add your apps to Installed apps
INSTALLED_APPS = [
'main',
'weblogin',
..........
]
# Now add TEMPLATE_DIR to 'DIRS' where in TEMPLATES like bellow
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, BASE_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',
],
},
},
]
# On end of Settings.py put this refferences to Static and Media files
STATICFILES_DIRS = [STATIC_DIR,]
STATIC_URL = '/static/'
MEDIA_ROOT = [MEDIA_DIR,]
MEDIA_URL = '/media/'
If you have problem with Database, please check if you put the original BASE_DIR bellow the new BASE_DIR otherwise change
# Original
'NAME': BASE_DIR / 'db.sqlite3',
# to
'NAME': os.path.join(BASE_DIR,'db.sqlite3'),
Django now will be able to find the HTML and Static files both in the App folders and in Root folder without need of adding the name of App folder in front of the file.
Struture:
-DjangoProject
-static(css,JS ...)
-templates(base.html, ....)
-other django files like (manage.py, ....)
-App1
-templates(index1.html, other html files can extend now base.html too)
-other App1 files
-App2
-templates(index2.html, other html files can extend now base.html too)
-other App2 files
- [Django]-Django Queryset with year(date) = '2010'
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-How to combine multiple QuerySets in Django?
0π
Another cause of the "template does not exist" error seems to be forgetting to add the app name in settings.py. I forgot to add it and that was the reason for the error in my case.
INSTALLED_APPS = [
'my_app',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
- [Django]-Setting DEBUG = False causes 500 Error
- [Django]-Django queries β id vs pk
- [Django]-Favorite Django Tips & Features?
- [Django]-What's the best way to extend the User model in Django?
- [Django]-Django-Forms with json fields
- [Django]-How to recursively query in django efficiently?
0π
My problem was that I changed the name of my app. Not surprisingly, Visual Studio did not change the directory name containing the template. Manually correcting that solved the problem.
- [Django]-Speeding up Django Testing
- [Django]-Django β how to visualize signals and save overrides?
- [Django]-Django return file over HttpResponse β file is not served correctly
0π
in TEMPLATES :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [r'C:\Users\islam\Desktop\html_project\django\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',
],
},
},
]
put the full directory of your templates file, then in views :
def home(request):
return render(request, "home\index.html")
start the path that after templates to the html file
in brief :
the full path is :
C:\Users\islam\Desktop\html_project\django\templates\home\index.html
-
C:\Users\islam\Desktop\html_project\django\templates
the full path to your template file will be in TEMPLATES in'DIRS': [' ']
-
home\index.html the path that comes after template will be in
render( )
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Django.contrib.auth.logout in Django
- [Django]-Django, Models & Forms: replace "This field is required" message
0π
For those that tried all the options here but still got the error, mine was a simple typo.
My template file was called "vacation_**list**.html"
, however, my view had a return render(request, 'vacation_**List**.html')
. Notice the uppercase L in list.
My development box didnβt seem to care about case sensitive file names but my production host did, so it couldnβt find the file due to the uppercase L.
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-UUID as default value in Django model
-1π
You should type 'templates'
to DIRS of TEMPLATES in your settings.py
file.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'], <--- type here!
'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]-Cannot access django app through ip address while accessing it through localhost
- [Django]-In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
- [Django]-Embed YouTube video β Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'