How to keep all my django applications in specific folder - python

I have a Django project, let's say "project1".
Typical folder structure for applications is:
/project1/
/app1/
/app2/
...
__init__.py
manage.py
settings.py
urls.py
What should I do if I want to hold all of my applications in some separate folder, 'apps' for example? So that structure should look like the following:
/project/
apps/
app1/
app2/
...
__init__.py
manage.py
settings.py
urls.py

You can add your apps folder to your python path by inserting the following in your settings.py:
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
Then you can use all the apps in this folder just in the same way as they were in your project root!

You can do this very easily, but you need to change the settings.py to look like this:
INSTALLED_APPS = (
'apps.app1',
'apps.app2',
# ...
)
And your urls.py to look like this:
urlpatterns = patterns('',
(r'^app1/',include('apps.app1')),
(r'^app2/',include('apps.app2')),
)
.. and modify any imports to point to the app location

How about you utilize the BASE_DIR variable already present in the settings.py.
Just add the following:
import sys
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
Hope this helps.

As a slight variant to Berhard Vallant's or Anshuman's answers, here is an alternative snippet to place in settings.py
import os
import sys # Insert this line
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Insert the two lines below
APPS_DIR = os.path.join(BASE_DIR, '<your_project_dir_name>/apps/')
sys.path.insert(0, APPS_DIR)
Doing it in this way has the added benefit that your template directories are cleaner as they will look like below. Without the APPS_DIR variable, there will be a lot of repitition of <your_project_dir_name>/apps/ within the DIRS list of the TEMPLATES list.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(APPS_DIR, '<app_name>/templates/<app_name>'),
os.path.join(APPS_DIR, '<app_name>/templates/<app_name>'),
...
],
'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 list the apps within the INSTALLED_APPS list as normal with either the short-form name given in apps.py or by using the long-form syntax of appname.apps.AppnameConfig replacing appname with your app's name.

It's easy and simple you need to add to settings.py
import os
import sys
PROJECT_ROOT = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps'))
and edit your app config for example
old app config:
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'myapp'
to new app config:
class MyappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
label='myapp'
name = 'apps.myapp'
than installed apps example:
INSTALLED_APPS = [
...
'apps.myapp.apps.MyappConfig'
...
]
I think it's very usefull and helpfull.Good luck :)

Just add __init__.py (4 underscores in total) in your apps folder. Now you can just do
urlpatterns = [
path('polls/',include('apps.polls.urls')),
path('admin/', admin.site.urls)
]

If you're using virtualenv/virtualenvwrapper (which is a bit dated but still valid), you can use the included add2virtualenv command to augment your python path:
mkdir apps
cd apps
pwd
[/path/to/apps/dir]
Copy that path to clipboard, then:
add2virtualenv /path/to/apps/dir

In my case, my project folder structure is the following:
/project/
/apps/
/app1/
/app2/
/src/
/settings.py
...
So I've solved it with these two lines on my settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(BASE_DIR, '../apps'))
No need to alter urls.py.

By using manage.py
# Fisrt create apps folder and appname subfolder
mkdir -p ./apps/<appname>
# Then create new app
python manage.py <appname> ./apps/<appname>

Related

Why can't my Django root url-conf find my app module?

I'm wondering if someone can help me. I am looking to restructure a new django project, to represent the below:
-repository/
-config/
-asgi.py
-settings.py
-urls.py
-wsgi.py
-__init__.py
-project root/
-app_1/
-admin.py
-apps.py
-models.py
-tests.py
-urls.py
-views.py
-__init__.py
-app_2/
-...
-app_3/
-...
-migrations/
-__init__.py
-static/
-templates/
-docs/
-manage.py
I have tried to implement this so far by appending the below lines to the settings.py file:
# This is the <repository root>
BASE_DIR = Path(__file__).resolve().parent.parent
# This is the <project repository>
PROJECT_ROOT = BASE_DIR / 'project'
MEDIA_ROOT = PROJECT_ROOT / 'media'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = PROJECT_ROOT / 'static_root'
STATIC_URL = PROJECT_ROOT / 'static'
ROOT_URLCONF = 'config.urls'
Templates = [{ ...
'DIRS': [PROJECT_ROOT / 'templates'],
... }]
In the installed apps I have to specify '.app1' vs traditionally just 'app1'. I amended the manage.py,wsgi.py,asgi.py file etc to point to the settings file.
However...
When I try to include() an app specific urlconf in the config root urlconf using the below:
from django.contrib import admin
from django.urls import path, include
import project.app1
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls', namespace='app1'))
]
it says
"ModuleNotFoundError: No module named 'app1'"
Please can someone advise if i am missing a step in this restructue and/or if i'm missing something in the url conf?
You add some subdirectory (project_root) to your app without add __init__.py. Django can't found your app1 path.
Try to register subdirectory to your Django path in settings.py
import sys
sys.path.append(os.path.join(BASE_DIR, 'project_root'))
Suggestion: Do not use whitespace to your Django module/directory
Add app1 in your INSTALLED_APPS in settings.py

Django can't find template directory

I know there are many questions similar to this one, but none has solved my problem yet.
Python version: 3.4
Django version: 1.8
I get TemplateDoesNotExist at /lfstd/ when loading http://127.0.0.1:8000/lfstd/.
system.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
lfstd/views.py:
def index(request):
[...]
return render(request, 'lfstd/index.html', context_dict)
project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
url(r'^admin/', include(admin.site.urls)),
url(r'^lfstd/', include('lfstd.urls')),
lfstd urls.py:
from django.conf.urls import patterns, url
from lfstd import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'))
Running print on base_dir and template_path, I get:
Base dir: C:\Users\Phil\PycharmProjects\TownBuddies
Template path: C:\Users\Phil\PycharmProjects\TownBuddies\templates
Which is exactly where my project and template folder is located. However, django doesn't look in that folder for templates. It looks in the following folders:
C:\Python34\lib\site-packages\django\contrib\admin\templates\lfstd\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\lfstd\index.html (File does not exist)
In fact, if I move my template there, it does find it and it works.
Any help is very appreciated, I'm starting out with Django and completely stuck...
EDIT:
I changed TEMPLATE_DIRS to TEMPLATES but Django still isn't looking in the templates folder:
TEMPLATE_DIRS setting is deprecated in django 1.8. You should use the TEMPLATES instead:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_PATH],
'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',
],
},
},
]
I was doing some unit testing with pytest-django when suddenly I was getting repeated and completely unexpected ** TemplateDoesNotExist** errors.
I found this stackoverflow question while trying to figure out what was going on.
I finally solved the issue by deleting all the __pycache__ directories. I have since learned that when things suddenly go inexplicably wonky to clear out the __pycache__ before breaking things by trying to fix them!
I used this script to clear out all the __pycache__ directories recursively where a module with the following resides:
#!/usr/bin/env python
import os
import shutil
#!/usr/bin/env python
import os
import shutil
BASE_DIR = os.path.abspath(__file__)
print(BASE_DIR)
for root, dirs, files in os.walk(BASE_DIR):
for directory in dirs:
if directory == '__pycache__':
shutil.rmtree(os.path.join(root, directory))

Django - include app urls

I have the following structure (Django 1.4):
containing_dir/
myproject/
myapp1/
myapp2/
myapp3/
myproject, myapp1, myapp2, and myapp3 all have init.py, so they're all modules.
In manage.py (under containing_dir) I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
in myproject.settings i define:
[..]
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = (
[..]
'myproject.myapp1',
'myproject.myapp2',
'myproject.myapp3',
)
[..]
In myapp1.urls.py I define:
urlpatterns = patterns('myapp1',
url(r'^agent/$', 'views.agent', name='agent')
)
and I try to import it in myproject.urls I try to import myapp1 urls like this:
(r'^myapp1/', include('myproject.myapp1.urls'))
but whenever I try lo load localhost:8000/myapp1/agent I get
Exception Value: No module named myapp1
I think thrown from withing myapp1.urls
Any help? thanks
You must have a
__init__.py
file inside your "myproject" directory. When you say:
(r'^myapp1/', include('myproject.myapp1.urls'))
you are saying "myproject" (as well as myapp1) is a python packege.
In myproject.settings make following changes :
INSTALLED_APPS = (
[..]
'myapp1',
'myapp2',
'myapp3',
)
Try:
urlpatterns = [
...
url(r'^app_name/', include('app_name.urls', namespace='project_name'))
...
]
Does ROOT_URLCONF need to point to myproject.urls?
If you place your apps inside of myproject you need to use the proper view prefix.
urlpatterns = patterns('myproject.myapp1',
...
To solve this issue just select "myproject" directory in PyCharm and set this as a source root.
Your project don't know from which root it has to search for given app.
It fixed the issue for me.
Thank you.
Recently, In new versions of Django introduces path(route, view, kwargs=None, name=None) instead of old url() regular expression pattern.
You must have __init__.py file in app folders to recognize it as a package by django project i.e myproject
Django project i.e. myproject urls.py file must be updated to include examples like:
path('', include('django_app.urls'))
path('url_extension/', include('django_another_app.urls'))
Above example includes two apps urls in it. One is without adding any extension to path in url and another is with extension to path in current url.
Also, Do not forget to add django apps in INSTALLED_APPS in settings.py file to recognise it as app by django project something like this.
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = [
...
django_app,
django_another_app
...
]
For more information look at documentation.

What is the path for TEMPLATE_DIRS in django settings.py when using virtualenv

I am using virtualenv and I want to know what the TEMPLATE_DIRS in settings.py should be, for example if I make a templates folder in the root of my project folder.
You need to specify the absolute path to your template folder. Always use forward slashes, even on Windows.
For example, if your project folder is "/home/djangouser/projects/myproject" (Linux) or 'C:\projects\myproject\' (Windows), your TEMPLATE_DIRS looks like this:
# for Linux
TEMPLATE_DIRS = (
'/home/djangouser/projects/myproject/templates/',
)
# or for Windows; use forward slashes!
TEMPLATE_DIRS = (
'C:/projects/myproject/templates/',
)
Alternatively you can use the specified PROJECT_ROOT variable and generate the absolute path by joining it with the relative path to your template folder. This has the advantage that you only need to change your PROJECT_ROOT, if you copy the project to a different location. You need to import the os module to make it work:
# add at the beginning of settings.py
import os
# ...
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates/'),
)
If you're working with a newer version of Django you may have to add it to the DIR list that is inside settings.py under TEMPLATES.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['[project name]/templates'], # Replace with your project name
'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',
],
},
},
]
the PROJECT_DIR has not been defined... the PROJECT_DIR is not a variable. its a directory/ a path to where the folder "templates" is located. This should help
import os
PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = os.path.join(PROJECT_DIR, 'templates')
TEMPLATE_DIRS deprecated
This setting is deprecated since Django version 1.8.
deprecated
""" settings.py """
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates/'),
)
correct
""" settings.py """
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ os.path.join(BASE_DIR, 'templates') ],
'APP_DIRS': True,
...
},
]
If you are using Django 1.9, it is recommended to use BASE_DIR instead of PROJECT_DIR.
# add at the beginning of settings.py
import os
# ...
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates/'),
)
Adding this in web/settings.py solved everything for me. Hope it can help you too.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
from os.path import join
TEMPLATE_DIRS = (
join(BASE_DIR, 'templates'),
)

Django TemplateDoesNotExist?

My local machine is running Python 2.5 and Nginx on Ubuntu 8.10, with Django builded from latest development trunk.
For every URL I request, it throws:
TemplateDoesNotExist at /appname/path appname/template_name.html
Django tried loading these templates, in this order:
* Using loader django.template.loaders.filesystem.function:
* Using loader django.template.loaders.app_directories.function:
TEMPLATE_DIRS
('/usr/lib/python2.5/site-packages/projectname/templates',)
Is it looking for /usr/lib/python2.5/site-packages/projectname/templates/appname/template_name.html in this case? The weird thing is this file does existed on disk. Why can't Django locate it?
I run the same application on a remote server with Python 2.6 on Ubuntu 9.04 without such problem. Other settings are the same.
Is there anything misconfigured on my local machine, or what could possibly have caused such errors that I should look into?
In my settings.py, I have specified:
SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))
# Find templates in the same folder as settings.py.
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
It should be looking for the following files:
/usr/lib/python2.5/site-packages/projectname/templates/appname1/template1.html
/usr/lib/python2.5/site-packages/projectname/templates/appname1/template2.html
/usr/lib/python2.5/site-packages/projectname/templates/appname2/template3.html
...
All the above files exist on disk.
Solved
It works now after I tried:
chown -R www-data:www-data /usr/lib/python2.5/site-packages/projectname/*
It's strange. I don't need to do this on the remote server to make it work.
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__))
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',
],
},
},
]
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'),
...
]
}
]
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',
],
},
},
]
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.
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'
]
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 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',
)
May, 2022 Update:
As long as you follow this tutorial properly, you don't need to change(touch) the default settings of "TEMPLATES" in "settings.py" as shown below:
# "core/settings.py"
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",
],
},
},
]
And again, as long as you follow this tutorial properly, "templates" can be read properly under application folders as shown below:
root
├── core
│   ├── settings.py
│   ├── urls.py
│   ...
├── myapp1
│   ├── templates
│   │   └── myapp1
│   │   └── myapp1.html
│   ├── urls.py
│   ├── views.py
│ ...
├── myapp2
│   ├── templates
│   │   └── myapp2
│   │   └── myapp2.html
│   ├── urls.py
│   ├── views.py
│ ...
And "templates" can be read properly under a root django project folder as shown below:
root
├── core
│   ├── settings.py
│   ├── urls.py
│   ...
├── myapp1
│   ├── urls.py
│   ├── views.py
│ ...
├── myapp2
│   ├── urls.py
│   ├── views.py
│ ...
├── templates
│   ├── myapp1
| | └── myapp1.html
| └── myapp2
| └── myapp2.html
So, the key things which you need to do are just don't change(touch) the default settings of "TEMPLATES" in "settings.py" as shown below:
# "core/settings.py"
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",
],
},
},
]
Then, set "myapp1" and "myapp2" applicatons to "INSTALLED_APPS" in "core/settings.py" as shown below:
# "core/settings.py"
INSTALLED_APPS = [
...
"myapp1",
"myapp2",
]
Then, write each "views.py" of "myapp1" and "myapp2" applications as shown below. Be careful, you need to write each "templates" path "myapp1/myapp1.html" and "myapp2/myapp2.html" instead of just writing each "templates" path "myapp1.html" and "myapp2.html" in "render()" as shown below:
# "myapp1/views.py"
from django.shortcuts import render
def myapp1(request): # Don't write just "myapp1.html"
return render(request, "myapp1/myapp1.html")
# "myapp2/views.py"
from django.shortcuts import render
def myapp2(request): # Don't write just "myapp2.html"
return render(request, "myapp2/myapp2.html")
Then, set each "views.py" path of "myapp1" and "myapp2" applications as shown below:
# "myapp1/views.py"
from django.urls import include, path
from . import views
urlpatterns = [
path("", views.myapp1, name='myapp1'), # Here
]
# "myapp2/views.py"
from django.urls import include, path
from . import views
urlpatterns = [
path("", views.myapp2, name='myapp2'), # Here
]
Then, set each path to "urls.py" of "myapp1" and "myapp2" applications in "core/urls.py" as shown below. Finally, The templates of "myapp1" and "myapp2" applications will be read without any errors:
# "core/urls.py"
from django.urls import include, path
urlpatterns = [
...
path("myapp1/", include('myapp1.urls')), # Here
path("myapp2/", include('myapp2.urls')), # Here
]
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.
Check permissions on templates and appname directories, either with ls -l or try doing an absolute path open() from django.
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?
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')],
I must use templates for a internal APP and it works for me:
'DIRS': [os.path.join(BASE_DIR + '/THE_APP_NAME', 'templates')],
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')],
...
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
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',
'.........',
]
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 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
Check that your templates.html are in /usr/lib/python2.5/site-packages/projectname/templates dir.
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:
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!
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
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.
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
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
Simple solution
'DIRS': [BASE_DIR, 'templates'],
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.
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',
]
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( )

Categories