Related
I have made a portfolio + blog website using Django. it works perfectly when running it locally but after I deployed it to Heroku, accessing the portfolio redirected me to a 500 server error. I turned on debug mode and when I did the same, it didn't throw a 500 server error, however, the pictures won't load. this is very confusing and help will be very appreciated...
settings.py
from pathlib import Path
import os
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'projects',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'personal_portofolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["personal_portofolio/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',
],
},
},
]
WSGI_APPLICATION = 'personal_portofolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
import django_heroku
django_heroku.settings(locals())
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'personal_portofolio.settings')
application = get_wsgi_application()
application = WhiteNoise(application)
what my project directory looks like:
C:.
├───blog
│ ├───migrations
│ │ └───__pycache__
│ ├───templates
│ └───__pycache__
├───personal_portofolio
│ ├───templates
│ └───__pycache__
├───projects
│ ├───migrations
│ │ └───__pycache__
│ ├───static
│ │ └───img
│ ├───templates
│ └───__pycache__
└───staticfiles
└───admin
├───css
│ └───vendor
│ └───select2
├───fonts
├───img
│ └───gis
└───js
├───admin
└───vendor
├───jquery
├───select2
│ └───i18n
└───xregexp
Edit: after setting DEBUG_PROPAGATE_EXCEPTIONS to True, I am getting this error in the Heroku logs ValueError: Missing staticfiles manifest entry for 'staticfiles/project1.png'
Your settings.py seems fine, try adding this code to project-name/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # add static file URL to django urlpatterns
If your trying to host media files note that Heroku does not support media hosting you might need to connect your Django application with something like amazon s3 bucket. You can find an article about it here.
I am trying to deploy a django react ecommerce app using aws ec2. when i run python manage.py runserver 0.0.0.0:8000 it is loading the page but not serving static files. The errors are
[24/Jun/2021 19:29:26] "GET / HTTP/1.1" 200 2297
[24/Jun/2021 19:29:26] "GET /static/css/2.97503911.chunk.css HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/css/main.4586955f.chunk.css HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/js/2.7e7fd32c.chunk.js HTTP/1.1" 404 179
[24/Jun/2021 19:29:26] "GET /static/js/main.002fbd2b.chunk.js HTTP/1.1" 404 179
Here is my settings.py file
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
from datetime import timedelta
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+^5qu3r54+4ja6q(_$rc!w4*z9t$erk61j=m8wbry53y*c-&h*'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = ['http://localhost:3000']
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = ['myamazonclone.ml']
SITE_ID = 1
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'dj_rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'dj_rest_auth.registration',
'rest_framework_simplejwt.token_blacklist',
'users',
'payment',
'products',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
# 'rest_framework.authentication.BasicAuthentication',
)
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
# 'SIGNING_KEY': settings.SECRET_KEY,
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'AUTH_HEADER_TYPES': ('Bearer', 'JWT'),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=60),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
REST_USE_JWT = True
JWT_AUTH_COOKIE = 'my-app-auth'
JWT_AUTH_REFRESH_COOKIE = 'users-refresh-token'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/'frontend'],
'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',
],
},
},
]
WSGI_APPLICATION = 'backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR/'static'
STATICFILES_DIRS = [BASE_DIR/'frontend/static']
AUTH_USER_MODEL = 'users.User'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
# E-mail address is automatically confirmed by a GET request
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
# Allow logins with an unverified e-mail address
ACCOUNT_EMAIL_VERIFICATION = 'none'
# REST_AUTH_REGISTER_SERIALIZERS = {
# 'REGISTER_SERIALIZER': 'users.serializers.CustomRegistrationSerializer'
# }
AUTHENTICATION_BACKENDS = [
'allauth.account.auth_backends.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
]
I have mentioned the STATIC_ROOT above and have also done python manage.py collectstatic. After doing so it makes a static folder in the root where manage.py is located and it also contains all the files the django is unable to find and gives 404. I also tried using gunicorn but still it is not able to serve static files. I donot understand what mistake i am making . Any help will be really appriciated.
Here is my file structure
Amazon Prod
├─ backend
│ ├─ asgi.py
│ ├─ settings.py
│ ├─ urls.py
│ ├─ wsgi.py
│ ├─ __init__.py
│ └─ __pycache__
│ ├─ settings.cpython-39.pyc
│ ├─ urls.cpython-39.pyc
│ ├─ wsgi.cpython-39.pyc
│ └─ __init__.cpython-39.pyc
├─ db.sqlite3
├─ frontend
│ ├─ asset-manifest.json
│ ├─ favicon.ico
│ ├─ index.html
│ ├─ logo192.png
│ ├─ logo512.png
│ ├─ manifest.json
│ ├─ robots.txt
│ └─ static
│ ├─ css
│ │ ├─ 2.97503911.chunk.css
│ │ ├─ 2.97503911.chunk.css.map
│ │ ├─ main.4586955f.chunk.css
│ │ └─ main.4586955f.chunk.css.map
│ └─ js
│ ├─ 2.7e7fd32c.chunk.js
│ ├─ 2.7e7fd32c.chunk.js.LICENSE.txt
│ ├─ 2.7e7fd32c.chunk.js.map
│ ├─ main.002fbd2b.chunk.js
│ ├─ main.002fbd2b.chunk.js.map
│ ├─ runtime-main.e2a9cdff.js
│ └─ runtime-main.e2a9cdff.js.map
├─ manage.py
├─ payment
├─ products
├─ requirements.txt
├─ static
└─ users
backend is the name of project. frontend is the production build react app.
here is my project urls.py file
from django import urls
from django.contrib import admin
from django.urls import path, include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from users.views import BlacklistTokenUpdateView
# Allows to render a template without a view
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('rest_framework.urls')),
path('dj-rest-auth/', include('dj_rest_auth.urls')),
path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('blacklist/', BlacklistTokenUpdateView.as_view(), name='blacklist'),
path('payment/', include('payment.urls')),
path('storeApi/', include('products.urls')),
path('', TemplateView.as_view(template_name='index.html'))
]
Check the ownership of the files. If you load your files as ec_user and try to deliver as www-data with 640 permissions you will have 404s.
wild bet.
I created a django app using openshifts default django quickstart app. But because it is based on django 1.4 I did the following changes
setup.py
#!/usr/bin/env python
from setuptools import setup
setup(
name='YourAppName',
version='1.0',
description='OpenShift App',
author='Your Name',
author_email='example#example.com',
url='http://www.python.org/sigs/distutils-sig/',
install_requires=['Django==1.6'],# changed this from Django <= 1.4
)
to instruct openshift to install Django 1.6. I also changed my manage.py to the one that Django 1.6 uses. I deployed it and I got a success message. But when visiting my web page it gives me a bad request.
directory tree
wsgi
├── application
├── beta_tree.txt
├── openshift
│ ├── __init__.py
│ ├── manage.py
│ ├── manage.py~
│ ├── openshiftlibs.py
│ ├── settings.py
│ ├── settings.py~
│ ├── settings.pyc
│ ├── sqlite3.db
│ ├── templates
│ │ └── home
│ │ └── home.html
│ ├── urls.py
│ └── views.py
└── static
└── README
settings.py
# -*- coding: utf-8 -*-
# Django settings for OpenShift project.
import imp, os
# a setting to determine whether we are running on OpenShift
ON_OPENSHIFT = False
if os.environ.has_key('OPENSHIFT_REPO_DIR'):
ON_OPENSHIFT = True
PROJECT_DIR = os.path.dirname(os.path.realpath(__file__))
if ON_OPENSHIFT:
DEBUG = bool(os.environ.get('DEBUG', False))
if DEBUG:
print("WARNING: The DEBUG environment is set to True.")
else:
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
if ON_OPENSHIFT:
# os.environ['OPENSHIFT_MYSQL_DB_*'] variables can be used with databases created
# with rhc cartridge add (see /README in this git repo)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'sqlite3.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': os.path.join(PROJECT_DIR, 'sqlite3.db'), # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.environ.get('OPENSHIFT_DATA_DIR', '')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_DIR, '..', 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
#ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make a dictionary of default keys
default_keys = { 'SECRET_KEY': 'secret_key' }
# Replace default keys with dynamic values if we are in OpenShift
use_keys = default_keys
if ON_OPENSHIFT:
imp.find_module('openshiftlibs')
import openshiftlibs
use_keys = openshiftlibs.openshift_secure(default_keys)
# Make this unique, and don't share it with anybody.
SECRET_KEY = use_keys['SECRET_KEY']
# 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',
#'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'openshift.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(PROJECT_DIR, 'templates'),
)
WSGI_APPLICATION = "wsgi.application"
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
I remember it being easier to deploy.
Hej! Many threads here had the same caption, but none of them solved my problem. I have a Django site an can access /admin (but it looks ugly). But on / there appears the following error page (DEBUG = True in settings.py):
TemplateDoesNotExist at /
index.html
Request Method: GET
Request URL: http://iecl.uni-potsdam.de/
Django Version: 1.4.5
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: /usr/lib/python2.7/dist-packages/django/template/loader.py in find_template, line 138
Python Executable: /usr/bin/python
Python Version: 2.7.3
Python Path:
['/home/python/iecl/lib/python2.7/site-packages/distribute-0.6.28-py2.7.egg',
'/home/python/iecl/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/pymodules/python2.7',
'/home/python/iecl/lib/python2.7/site-packages',
'/home/django/django']
Server time: Mon, 7 Apr 2014 11:28:46 +0200
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/django/django/templates/iecl_dev/index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/usr/lib/python2.7/dist-packages/django/contrib/auth/templates/index.html (File does not exist)
/usr/lib/python2.7/dist-packages/django/contrib/admin/templates/index.html (File does not exist)
In fact, the file /home/django/django/templates/iecl_dev/index.html does exist and I also tried chmod o+r index.html without success.
The output of python iecl_dev/manage.py runserver 0.0.0.0:0 is
Validating models...
0 errors found
Django version 1.4.5, using settings 'iecl_dev.settings'
Development server is running at http://0.0.0.0:0/
Quit the server with CONTROL-C.
so everything seems fine here.
What perplexes me: The *.pyc files are created automatically when *.py files are run, right? After python iecl_dev/manage.py runserver 0.0.0.0:0 there is a file /home/django/django/iecl_dev/settings.pyc created. But it is not created, when I load the page in my web browser. Does that mean, the settings.py is never loaded? And how can Django say, a file, which exists, would not exist?
Edit¹:
My settings.py looks as follows:
import django.conf.global_settings as DEFAULT_SETTINGS
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
)
SETTINGS_PATH = os.path.realpath(os.path.dirname(__file__))
MANAGERS = ADMINS
DATABASES = { $
'default': { $
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'iecl', # Or path to database file if using sqlite3.
'USER': 'iecl', # Not used with sqlite3.
'PASSWORD': '<xxx>', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3. $
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
TIME_ZONE = 'Europe/Berlin'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
MEDIA_ROOT = '/var/www/django_media/iecl_dev/media/'
MEDIA_URL = ''
ADMIN_MEDIA_PREFIX = '/media/admin_media/'
SECRET_KEY = '<xxx>'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'iecl_dev.urls'
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'iecl_dev.showStudents',
'django.contrib.admin',
)
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
)
Edit²:
The contents of `/home/django/django/` are as follows:
/home/django/django/:
iecl2
iecl_dev
templates
/home/django/django/iecl2:
__init__.py
__init__.pyc
manage.py
settings.py
settings.pyc
showStudents
urls.py
urls.pyc
/home/django/django/iecl2/showStudents:
__init__.py
__init__.pyc
admin.py
context_processors.py
models.py
models.pyc
views.py
views.pyc
/home/django/django/iecl_dev:
__init__.py
__init__.pyc
manage.py
piwik
settings.py
settings.pyc
showStudents
urls.py
urls.pyc
/home/django/django/iecl_dev/piwik:
__init__.py
app_settings.py
context_processors.py
models.py
tests.py
urls.py
views.py
/home/django/django/iecl_dev/showStudents:
__init__.py
__init__.pyc
admin.py
context_processors.py
models.py
models.pyc
views.py
/home/django/django/templates:
iecl
iecl_dev
/home/django/django/templates/iecl:
500.html
admin
changePW.html
editStudent.html
feedback.html
feedback_thanks.html
index.html
location.html
login.html
page.html
password_changed.html
showStudent.html
studentsOverview.html
/home/django/django/templates/iecl/admin:
404.html
500.html
actions.html
app_index.html
auth
base.html
base_site.html
change_form.html
change_list.html
change_list_results.html
date_hierarchy.html
delete_confirmation.html
delete_selected_confirmation.html
edit_inline
filter.html
includes
index.html
invalid_setup.html
login.html
object_history.html
pagination.html
prepopulated_fields_js.html
search_form.html
showStudents
submit_line.html
/home/django/django/templates/iecl/admin/auth:
user
/home/django/django/templates/iecl/admin/auth/user:
add_form.html
change_password.html
/home/django/django/templates/iecl/admin/edit_inline:
stacked.html
tabular.html
/home/django/django/templates/iecl/admin/includes:
fieldset.html
/home/django/django/templates/iecl/admin/showStudents:
pagecontent
userpagecontent
/home/django/django/templates/iecl/admin/showStudents/pagecontent:
change_form.html
/home/django/django/templates/iecl/admin/showStudents/userpagecontent:
change_form.html
/home/django/django/templates/iecl_dev:
500.html
__init__.py
admin
changePW.html
editStudent.html
feedback.html
feedback_thanks.html
index.html
location.html
login.html
page.html
password_changed.html
piwik
showStudent.html
studentsOverview.html
/home/django/django/templates/iecl_dev/admin:
404.html
500.html
actions.html
app_index.html
auth
base.html
base_site.html
change_form.html
change_list.html
change_list_results.html
date_hierarchy.html
delete_confirmation.html
delete_selected_confirmation.html
edit_inline
filter.html
includes
index.html
invalid_setup.html
login.html
object_history.html
pagination.html
prepopulated_fields_js.html
search_form.html
showStudents
submit_line.html
/home/django/django/templates/iecl_dev/admin/auth:
user
/home/django/django/templates/iecl_dev/admin/auth/user:
add_form.html
change_password.html
/home/django/django/templates/iecl_dev/admin/edit_inline:
stacked.html
tabular.html
/home/django/django/templates/iecl_dev/admin/includes:
fieldset.html
/home/django/django/templates/iecl_dev/admin/showStudents:
pagecontent
userpagecontent
/home/django/django/templates/iecl_dev/admin/showStudents/pagecontent:
change_form.html
/home/django/django/templates/iecl_dev/admin/showStudents/userpagecontent:
change_form.html
/home/django/django/templates/iecl_dev/piwik:
tracking.html
Edit³:
Ok. This is solved for me now. The solution was a conglomerate of different things. One of the problems was the missing rights. The user that executes Django, could not list the contents of the templates/ directory. chmod o+x templates/ did the job. Then there were some settings in the settings.py, that changed the place to look for the templates from templates/iecl_dev/ to iecl_dev/templates/. I saw this wrong path in the error message in my web browser. But simply reverting the settings.py to the old version, was not enough. Some service(s) needed to be restarted. I simply rebooted the machine and everything was fine. Miraculously, the /admin/ page now looks nice as well.
Many thanks for all your tips.
From what you've shown, I think you may have a problem with your project layout.
Usually, it is set as follows :
├── manage.py
├── yourproject
│ ├── __init__.py
│ ├── settings.py
│ ├── templates
│ ├── urls.py
│ ├── wsgi.py
│ └── wsgi.pyc
├── yourfirstapp
│ ├── __init__.py
│ ├── admin.py
│ ├── models.py
│ ├── templates
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── yoursecondapp
├── __init__.py
├── admin.py
├── models.py
├── templates
├── tests.py
├── urls.py
└── views.py
As you can see, each app inside your project can have it's own templates directory.yourproject is a bit particuliar, because it also stores unique files, such as settings.pyand wsgi.py. However, you can consider and use it as an app.
Now, if you want to use a template stored in yourproject/templates, you'll have to add yourproject to your INSTALLED_APPS settings.
Does it helps ? If not, can you edit your original post with your project layout ?
I wasted a lot of time trying to figure out what was wrong with my 'templates' directory and figured out :
You may have forgotten to add TEMPLATE_DIR in the following segment of 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',
],
},
},
]
So it should have 'DIRS': [TEMPLATE_DIR,], instead of 'DIRS': [],
The reason might be that django is trying to look for your templates directory in the directory with your setting.py file
Whereas actually the templates directory is in the parent directory.
Try doing something like this in your settings.py
SETTINGS_PATH = os.path.dirname(__file__)
PROJECT PATH = os.path.join(SETTINGS_PATH, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATES_PATH = os.path.join(PROJECT_PATH, "templates")
TEMPLATE_DIRS = (
TEMPLATES_PATH,
)
The error usually is due to incorrectly configured templates directory
I know this is late, but the solutions mentioned here did not work for me. So here is what works:
inside the settings.py file, add your appConfig in installed apps.
INSTALLED_APPS = [
'...',
'AppName.apps.AppNameConfig',
]
create a templates directory appName/templates/appName. (where appName is the name of your app).
When you call your render function, then you can pass it templates.name.html. Like so:
return render(request, 'templates/blog.html')
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( )