I am new to Django. I made a folder named templates in my project and "base.html" inside it, it works fine. But when I make new folder inside templates welcome and then "home.html" and I write some lines of code in my views.py file as
from django.shortcuts import render_to_response
def hello(request):
return render_to_response('welcome/home.html')
and settings.py includes
# Django settings for Telecom project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
import os
#BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR = os.path.dirname(__file__)
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'mysql', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# 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 = 'UTC'
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.path.join(PROJECT_DIR, 'media')
# 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 = 'http://localhost:8000/media/admin/'
# 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 = ''
# 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 this unique, and don't share it with anybody.
SECRET_KEY = 'b9_hyqe*b&ra_&wlm5a9xas_ag#5mjv-dy=to%hdk_u-#xvn*l'
# 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',
)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
print PROJECT_DIR
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 = 'Telecom.urls'
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',
'welcome',
)
# 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,
},
}
}
but the error shows
TemplateDoesNotExist at /hello/
/welcome/home.html
Request Method: GET
Request URL: http://localhost:8000/hello/
Django Version: 1.6
Exception Type: TemplateDoesNotExist
Exception Value:
/welcome/home.html
Exception Location: C:\Python27\django\template\loader.py in find_template, line 131
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Windows\\SYSTEM32\\python27.zip']
Server time: Tue, 18 Jun 2013 17:09:07 +0545
How can I solve it ?
For Django 1.8 or above
you need to open the settings.py file and add the template path in the DIRS key of TEMPLATES list as a list of string.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['Secondjango/Secondjango/templates/welcome'], # <<<<<<<<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',
],
},
},
]
Thanks.
This error may arises due to the incorrect template directories
Try some change on settings.py as below
import os.path
Temp_Path = os.path.realpath('.')
...
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
...
TEMPLATE_DIRS = (
Temp_Path +"/template"
)
Then put all your template inside template folder and css/javascript file in static folder which is located inside your application folder. Hope this will solve your problem.
My suggestion don't put template folder inside application folder
Django will choose the first template it finds whose name matches, and
if you had a template with the same name in a different application,
Django would be unable to distinguish between them. We need to be able
to point Django at the right one, and the easiest way to ensure this
is by namespacing them. That is, by putting those templates inside
another directory named for the application itself.
Try this:
In your settings.py file replace
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
with
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
os.path.join(PROJECT_DIR, 'templates/welcome')
)
Then, in your code, just call render_to_response("home.html")
That should resolve your issue.
For Django 1.8 or above just Add the following in TEMPLATES DIR variable list in settings file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
This property points to template directory 'DIRS': ['templates'],
For Django 2.0, I edited the value DIRS of TEMPLATES in setting file to the entry directory of the project:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['.'], # here set DIRS to project's entry directory
'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 the problem solved on both Mac and Windows systems.
You can use:
in settigns.py
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),)
STATICFILES_DIRS = (
'static',
)
Please check if you have added your new application in the settings.py file under INSTALLED_APPS
Django compiles all the 'templates' folder from all the applications inside your project into a single 'templates' folder.
Please remember to create separate directory inside your applications 'template' folder to make it easier for the Django framework to find the template you are looking for.
suppose that you hace a django project "my_project", and the application "app_1" and "app_2"
my_project
-- my_project
-- manage.py
welcome
-- __init__.py
templates
-- home.html
-- models.py
-- views.py
app_1
-- __init__.py
templates
welcome
-- home.html
-- models.py
-- views.py
app_2
templates
a_subfolder
-- home.html
-- __init__.py
-- models.py
-- views.py
now, if you have some settings like.
#...
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
#...
INSTALLED_APPS = (
'app_2',
'app_1',
'welcome',
#...
)
#...
django will do that:
When you call render_to_response('welcome/home.html') (I think that some params are missing), django will look at "home.html" file in some some "welcome" folder in ALL aplications (in this case "app_1" and "app_2") that have a "templates" folder. (that is a convention)
EDIT
I have added you "welcome" app.
You have to call the method without app name render_to_response('home.html')
Check if there is any include tag in "hello.html" which has been given filepath that does not exist. The error raised comes up the same :-
TemplateDoesNotExist at /hello/
/welcome/home.html
Add template directory to your TEMPLATES in your project settings.py by 'DIRS': [os.path.join(BASE_DIR, 'templates')],
So the final TEMPLATES should be something like the following
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Do this
-> Make sure your templates folder should be in root folder not in app folder
-> then goto your setting.py file and look for TEMPLATES = [ 'DIRS': ]
-> in DIRS put the path of your template folder like this 'DIRS':[r'path']
it will work
Another reason could be if the name of the folder in your app is template and not templates. Note 's' in the end.
Your settings.py file must be :
'DIRS': ["templates"]
Your templates folder must be under your main project name :
Like that
All I had to do was Install 'rest_framework' as one of the apps.
Have you created the file __init__.py inside your welcome folder?
Related
I am new to python and Django. I have a base.html file in my root directory. I have a hello_world.html file in my personal_portfolio app's template file that contains {% extends "base.html" %} in hello_world.html. I have the appropriate entry in the 'DIRS': settings of my personal_portfolio project. I get a template not found error for base.html.
In the debug info I see reference to 'django.template.loaders.app_directories.load_template_source'. My impression is that when 'APP_DIRS': is True, this loader is responsible for automatically loading each apps template file in a list of directories to search for templates. I see no reference to ' 'django.template.loaders.filesystem.load_template_source' which I understand is responsible for adding directories in the 'DIRS': setting to the search list. This is how base.html should be located. However, it seems that no matter what I do only the 'django.template.loaders.app_directories.load_template_source' loader is used.
I even tried including a setting for TEMPLATE_LOADERS in settings.py.
What I did as a workaround is modify the the app_directories.py module to add the directory I am pointing to in the 'DIRS': setting. Here is the app_directories modification in E:\Python Programs\Web Projects II\rp_portfolio\venv\Lib\site-packages\django\template\loaders\app_directories.py.
#************** Revised app_directories.py
"""
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
packages.
'''
from django.template.utils import get_app_template_dirs
from .filesystem import Loader as FilesystemLoader
class Loader(FilesystemLoader):
def get_dirs(self):
# ## return get_app_template_dirs('templates')
#esr revised 8/22/19
dirtup = get_app_template_dirs('templates')
dirlst = list(dirtup)
dirlst.append('E:\\Python Programs\\Web Projects II\\rp_portfolio\\templates')
dirtup2 = tuple(dirlst)
print('\n****************** app_directories.py: dirtup2:', dirtup2,'\n')
print('\n****************** app_directories.py: __file__ value:',__file__,'\n') !
return dirtup2
Above code worked and enabled locating "base.html" worked.
Why doesn't base.html load the normal way?
settings.py in personal_portfolio
"""
Django settings for personal_portfolio project.
Generated by 'django-admin startproject' using Django 2.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print('\n***********BASE_DIR:', BASE_DIR,'\n')
projecttemplates = (os.path.join(BASE_DIR,'templates\\'))
print('\n*******projecttemplates:', projecttemplates,'\n')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '-lql%2p2#5xy^s)fw#poz7qiw#r3rj%#_)$aufs)dpe*xs#xgr'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = 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',
'hello_world',
]
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',
]
ROOT_URLCONF = 'personal_portfolio.urls'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
)
# 'django.template.loaders.app_directories.load_template_source',
MASTER_BASE_DIR = BASE_DIR
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(MASTER_BASE_DIR,'templates\\')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
print('\n************ TEMPLATES:',TEMPLATES,'\n')
WSGI_APPLICATION = 'personal_portfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.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/2.2/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/2.2/howto/static-files/
STATIC_URL = '/static/'
Directory Structure
I have been working on a personal profile site and have an image for my cover page saved in my root static folder. I can see the cover image fine in the browser when debug is true but when debug is false or I am in production the file is a 404 error, nowhere to be found.
The root directory also has a CSS file (style.css) and a favicon.ico which both show up fine when debug is set to false or I am in production, it is just the image that doesn't show/work.
I also have a background image in the "Polls" app that shows up fine in both debug=false and production.
Here is an image of my file directory:
Here is my settings.py which, based on Django documentation and Heroku deployment documentation, should be configured correctly:
import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'NUNYABIZNESS'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))
ALLOWED_HOSTS = [
'still-atoll-90110.herokuapp.com',
'localhost',
'www.dominicscotto.org',
]
# Application definition
INSTALLED_APPS = [
'blog.apps.BlogConfig',
'polls.apps.PollsConfig',
'projects.apps.ProjectsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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',
]
ROOT_URLCONF = 'myportfolio.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myportfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
DATABASES = { 'default': dj_database_url.config(conn_max_age=600)}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = None
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
I tried calling the image from both the css:
body {
background: white url("images/Cover_image.jpeg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
and the head of the base.html:
<style> body { background-image: url(images/Cover_image.jpeg);} </style>
But it doesn't seem to be an issue with how I am calling for the image, it just isn't there in the browser.
When I run collectstatic it seems to be finding and grouping the files in "staticfiles" correctly:
Directory showing statifiles
I believe it has something to do with the image being in the root static folder but I am not clear why Django doesn't like it there vs. in a specific app. Any help would be greatly appreciated.
I am using Django 2.1 and Python 3.7.0
as in official documentation:
In your templates, use the static template tag to build the URL
for the given relative path using the configured STATICFILES_STORAGE.
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image">
and I think that in css you must use real path, Django doesn't serve css files with django template system. In your example, it would be
body {
background: white url("static/images/Cover_image.jpeg");
...
}
also, you can check the availability of your static files on production just use right path, that will start with static/ in your case.
Solved: Cover_Image.jpeg has a capital I in image which was not what I had in my css or head file. A case of missed capitalization due to bad naming convention.
I have changed Cover_Image.jpeg to cover_image.jpeg and in my CSS I'm using:
background: white url("images/cover_image.jpeg");
I also had to run:
python manage.py collectstatic --clear
for Django to catch these static files with Debug set to false
Python 3, Django 2.0
I just got to the end of the official Django tutorial, and I'm working on the advanced portion - "How to write reusable apps"
It seems like I was at least partially successful, I can access the Questions and Choices through the admin interface, but when I try to display the http://127.0.0.1:8000/polls/ I get this error: TemplateDoesNotExist at /polls/1/
I get a similar error for trying to access a detail page, at http://127.0.0.1:8000/polls/1/
I looked through all the troubleshooting questions I could, and my main question is - how can you access templates that are packaged into an app? The thing I see going wrong is that Django is trying to find the app templates inside the main project directories(ie: /tutorial/templates/polls/detail.html), but they should be "inside" the module I imported from pip.
Are you actually supposed to package the templates into apps this way? I tried throwing the template files back into tutorial/templates/polls/ and it works just fine, but this goes against what I think should be "reuseability" because then the packaged app won't have it's own templates.
The answers I was able to find seem to be more for older versions of Django, and used a TEMPLATE_LOADERS setting... Anyone know if there is a way to set that in Django 2?
Directory structure:
django-polls/
LICENSE
manifest.in
README.rst
setup.py
/dist
/docs
/polls
admin.py
apps.pyo
__init__.py
models.py
tests.py
urls.py
views.py
/build
/migrations
/static
/polls
/images
style.css
/templates
/polls
detail.html
index.html
results.html
The project structure is like this:
tutorial/
/mysite (settings.py, etc)
/templates
/admin
base_site.html
index.html
/venv (my virtualenv directory)
db.sqlite3
manage.py
settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*e7#6=f$r(cu_p#7#*s+6t9r^ouio$x&06s61-0u(n1mo370c6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# 'polls.apps.PollsConfig',
'polls',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# 'DIRS': [os.path.join(BASE_DIR, 'templates', 'polls')],
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/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/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
The issue here was case: the file had been named manifest.in, when it needed to be capitalized as MANIFEST.in. Happy holidays!
Remember to include your templates directory in your MANIFEST.in file. See step 6 of packaging your app for more info.
I use django and my site works perfect but cant load images. I guess wrong thing is paths but i can't fix it. I see questions like that and apply all of them to my site but they did not work, please someone help me, i can't solve that for a few days.
NOTE : my site works fine on localhost, on my computer but don't work on server
Create a folder called static in your project directory or your app directory. Create another folder inside static called images.
In your settings.py file, add this line.
STATIC_URL = '/static/'
In your template file add this to the first line.
{% load static %}
In your template, use code like this to get the image to show.
<img src="{% static "image/example.jpg" %}"/>
Add the following lines in settings.py.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
Finally go to your server project folder and use the following command.
python manage.py collectstatic
This command will copy all static files (e.g. images) from you static folders and paste it in folder you mentioned in STATIC_ROOT, in this case the folder is staticfiles.
Hope this helps.
Not sure if this is still of interest, but have been having the same problem and I had to do some searching. Here is the solution (https://docs.djangoproject.com/en/3.2/howto/static-files/deployment/ )
My understanding is that STATIC_ROOT acts as a "management repository" after you run collectstatic, and Django doesn't serve the files from there. You need to set up a separate folder. This is because in production, as flagged above, the suggestion is to have a separate server dedicated to such files.
In my case, I just created a separate folder next to static,
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'),)
Note, that this is NOT THE RECOMMENDED PLACE to PUT IT, and the above STATICFILES_DIRS should be separate, OUTSIDE your project folder/on a separate server. I put it there as my project was small, for testing purposes.
As flagged in the official documents too, you need to run collectstatic everytime a file there changes, and AFTER THAT you need to COPY THE FILES to the directory from where they are actually served, ie the directory that DJANGO is actually reading.
No changes are needed to the template(s).
Small add-on: the above is necessary (at least I found it so) for media/image files. Does not apply to the css/js files, which work just fine out of the normal '/static/' folder. Wanted to add this as I found LOTS of guides/explanations about setting up this '/static/' folder and collect static, but almost none about taking the additional step of moving images to a separate folder, STATICFILES_DIRS (or whatever name you want to set).
it is not about path, i guess. Becuse here is another basic project
enter image description here
views
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1><img src='static/ben2.jpg'></h1>")
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See
https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'key
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['my_server_ip']
# Application definition
INSTALLED_APPS = [
'webapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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',
]
ROOT_URLCONF = 'web.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'web.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/howto/static-files/
STATIC_URL = '/static/'
I have tried all combinations like what you said :D but they did not help me
Below STATIC_URL line, insert this :
STATIC_ROOT = os.join.path(BASE_DIR, 'static')
I am using python 3.4, django 1.8. I am using pycharm for developing. While running the program ,I am getting 'No module named 'django.templates'' error.
settings.py
"""
Django settings for dj project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uhqkhi7h_w48bz*gnr+_!roaa8#c_)087a(!ees)mn2=n=lv-r'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = 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',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'dj.urls'
TEMPLATES = [
{
'BACKEND': 'django.templates.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.templates.context_processors.debug',
'django.templates.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.load_template_source',
)
WSGI_APPLICATION = 'dj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/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/1.8/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
blog/urls.py
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^$', views.post_list),
]
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dj.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
post_list.html
<html>
<body>
<p>
hihiiii
</p>
</body>
</html>
dj/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include('blog.urls')),
]
Error
ImportError at /
No module named 'django.templates'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.8.1
Exception Type: ImportError
Exception Value:
No module named 'django.templates'
Exception Location: C:\Python34\lib\importlib\__init__.py in import_module, line 109
Python Executable: C:\Python34\python.exe
Python Version: 3.4.1
Python Path:
['C:\\Users\\ankur anand\\PycharmProjects\\dj',
'C:\\Users\\ankur anand\\PycharmProjects\\dj',
'C:\\Windows\\SYSTEM32\\python34.zip',
'C:\\Python34\\DLLs',
'C:\\Python34\\lib',
'C:\\Python34',
'C:\\Python34\\lib\\site-packages']
Server time: Fri, 15 May 2015 18:08:59 +0530
This can happen if you are not familiar with Pycharm IDE refactoring.
You renamed the "templates" directory to another name by refactoring.
When you do this, Pycharm also renames some strings in "settings.py".
Solution: Right click your "setting.py":
LocalHistory -> ShowHistory then restore you "setting.py".
Use this and replace it existing values. As in last post he told you that you just needed to remove "s" from relevant fields. But if you couldn't understand it then just copy paste.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
As the error mentions, there's no such thing as django.templates.
However, there is a django.template. You'll want to remove the s from all of the relevant lines that refer to templates.
While you're at it, you should also move your TEMPLATE_LOADERS to their proper location (within the TEMPLATES setting).
Read more in the docs.
I got the same exception with you when start my first django project...
i think maybe you changed the template dir name from 'template' to 'templates' in pycharm ,but didn't aware that pycharm changed the TEMPLATES.context_processors configs in setting.py at the sametime. it changed
django.template.context_processors.debug
django.template.context_processors.request
to
django.templates.context_processors.debug
django.templates.context_processors.request
.it's the cause of the problem.
This did happened due to Refactoring in Pycharm. I faced the same issue initially, when changed the directory name "template" to "templates".
To resolve this: Right click settings.py > local history > show history > revert.
It reverted the changes made in the settings file due to refactoring but kept the directory name to "Templates". Hence, resolving the issue.
in settings.py templates list is having key name DIRS that is empty, it should not be 'DIRS':[], RIGHT WAY -> add that value 'DIRS':[BASE_DIR / 'templates'] in settings.py
True, it is related to refactoring directory name from template to templates in my case.Need to correct change settings.py file under TEMPLATES(for me error was no module found "django.template" )
changes to be made under TEMPLATES is remove "s" from
django.templates.context_processors.debug
django.templates.context_processors.request
to:
django.template.context_processors.debug
django.template.context_processors.request