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
Related
Hi I have finished my Django pycharm project and I'm now trying to upload it to heroku/ host it on heroku. I have followed this link https://medium.com/#qazi/how-to-deploy-a-django-app-to-heroku-in-2018-the-easy-way-48a528d97f9c which has actually successfully worked for me in the past. When I get to the step were you put this command in however 'heroku run python manage.py migrate' I continue to get this error message 'Running python manage.py migrate on ⬢ radiant-retreat-19016... up, run.6371 (Free)
python: can't open file 'manage.py': [Errno 2] No such file or directory'
Im not that much of a beginner so I know that my manage.py file is in the right place especially cause I can run ' python manage.py runserver '. I will attach the code to my procFile below along with my manage.py code and settings. I have looked everywhere on the internet for the problem and some people have it but nothing has worked for them. I will attach any other code if you need it. I even transferred all code to a new project and the same problem occurred.
web: gunicorn inspect_list2.wsgi
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inspect_list2.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
"""
Django settings for inspect_list project.
Generated by 'django-admin startproject' using Django 2.2.14.
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
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# 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 = 'not showing this but its there'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
#'auth',
]
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 = 'inspect_list2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'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 = 'inspect_list2.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/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
AUTH_USER_MODEL = 'my_app.CustomUser'
LOGIN_REDIRECT_URL = 'front_page'
LOGOUT_REDIRECT_URL = 'home'
django_heroku.settings(locals())
Fixed by this
heroku run python **FOLDER**/manage.py migrate
ex
heroku run python HOME/manage.py migrate
I finally figured it out after 10 hours. Other sources online were right. If you refer to the link I posted above at the very bottom command. If you run the git push stuff first than that last command and after that you run the heroku migrate command it should work. WAIT! If it doesn't work then if you have touched your git repository stuff or changed the name or messed with your squilte3 file and you didn't know what you were doing then transfer all your code to another project so the git stuff and squilte3 stuff automatically is made and resets then follow the instruction in this comment again. If not I don't know what to tell you but it worked for me.
You can try this. Right click manage.py file and look for the option of open in terminal when it does run the code again
My application sits at the server path /home/myapp/.
The static assets sit at /home/myapp/src/static/ when a python manage.py collectstatic is performed.
It copies assets from /home/myapp/src/assets/.
I have tried with DEBUG both True and False.
When I navigate to the web application at https://test.example.com, it tells me that all of the assets that reside at /home/mpapp/src/assets/ are 404 (Not Found) despite the files being there.
Also, my web server setup is Apache with a reverse proxy to Gunicorn. I'm serving the application with gunicorn wsgi which serves the application at 127.0.0.1:8000, which is where Apache is ProxyPass to. I've tested against a brand new Django application and this setup serves it properly, so it shouldn't be how Apache and Gunicorn are configured.
What I have been doing is:
1) npm start to compile the React front-end assets
2) python manage.py collectstatic to move the assets to /static/
3) Run gunicorn wsgi where the manage.py and wsgi.py reside
Some code would be helpful. Here is my settings.py:
import os
import sys
import json
import datetime
from unipath import Path
from django.core.exceptions import ImproperlyConfigured
# Import JSON file
print(Path(__file__))
with open('./config/config.json') as f:
s = json.loads(f.read())
def get_settings(settings, s=s):
try:
return s[settings]
except KeyError:
error_msg = 'Set the {0} environment vaiable'.format(settings)
raise ImproperlyConfigured(error_msg)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).ancestor(2)
# Quick-start development settings - unsuitable for production
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_settings('SECRET_KEY')
ALLOWED_HOSTS = [
'*',
]
# Application definition
INSTALLED_APPS = [
# Base packages
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party packages
'rest_framework',
'rest_framework_jwt',
'webpack_loader',
'tinymce',
# Local packages
'authentication',
'documents',
'contact',
'home',
'results',
'users'
]
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 = 'config.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',
],
},
},
]
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_settings('DEBUG')
WSGI_APPLICATION = 'wsgi.application'
# Password validation
AUTH_USER_MODEL = 'authentication.User'
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',
},
]
# REST Framework settings
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
# DRF JWT token settings
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
'JWT_ALLOW_REFRESH': True,
}
# Webpack settings
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'bundles/',
'STATS_FILE': os.path.join(BASE_DIR, './config/webpack-stats.json'),
}
}
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# EMAIL SETTINGS
EMAIL_HOST = get_settings('EMAIL_HOST')
EMAIL_HOST_USER = get_settings('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = get_settings('EMAIL_HOST_PASSWORD')
EMAIL_PORT = get_settings('EMAIL_PORT')
EMAIL_USE_TLS = True
My directory structure looks like the following which is based on Two Scoops:
testapp
assets
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
scss
config
config.json
settings.py
urls.py
webpack.config.js
react
index.jsx
static
admin
bundles
css
app.e1c352f1.css
js
vendor.s63d4f.js
manifrest.5fd4g.js
app.dsr5h4.js
css
bootstrap.css
img
rest_framework
scss
templates
index.html
manage.py
wsgi.py
Also, my urls.py if that might be relevant:
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic.base import TemplateView
from home.views import GetHomeAPIView
urlpatterns = [
# Admin URL
url(r'^admin', admin.site.urls),
# API authentication entry point
url(r'^api/auth/', include('authentication.urls', namespace='signin')),
# API /home entry point
url(r'^api/home/', GetHomeAPIView.as_view(), name='home'),
# API /contact entry point
url(r'^api/contact/', include('contact.urls', namespace='contact')),
# API /contact entry point
url(r'^api/users/', include('users.urls', namespace='users')),
# Any requets that come through serve the index.html
url(r'^$', TemplateView.as_view(template_name='index.html')),
]
So not sure 100% what to do.
I have tried changing both STATIC_ROOT and STATIC_URL to the actual path /home/myapp/src/static/ which didn't do anything.
A bit stumped as to how to resolve this and the SO questions I have reviewed have not fixed the issue.
Well, I got things to start loading by doing the following in urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Also can be read about here.
https://docs.djangoproject.com/en/dev/howto/static-files/#serving-static-files-during-development
It is working, but that being said, the sections is called "Serving static files during development"... I'm doing this for production.
I am unable to load static files in production, whereas they work on local machine.
I have followed the steps in https://devcenter.heroku.com/articles/django-assets
as well as the existing answers but I am not able to make it run. I am overlooking something and would like the community's assistance.
Here is the partial settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ALLOWED_HOSTS = ['tryml.herokuapp.com','localhost']
# Application definition
INSTALLED_APPS = [
'web.apps.WebConfig',
'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 = 'tryml.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 = 'tryml.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 = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
Here is the wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tryml.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
Here is the html file trying to access the static content:
{% extends "web/base.html" %}
{% load static %}
{% block content %}
<div>
<img src="{% static 'web/img/target.jpg' %}" alt="Image could not be loaded"></img>
</div>
{% endblock %}
Here is the project structure:
tryml
--static
--web
--img
--target.jpg
--tryml
--settings.py
--wsgi.py
--urls.py
--web(web app)
--(urls,forms,templates,...)
--manage.py
--Procfile
--requirements.txt
--runtime.txt
One more observation, when I check the requests sent from my browser, it shows a 404 error for the static file(image) and says it tried to lookup here- ...herokuapp.com/static/web/img/target.jpg
Shouldn't it refer from STATIC_ROOT(staticfiles/web/img/target)?
EDIT-- The collectstatic command runs when the code is pushed on heroku,and it shows a successful copy step into app/staticfiles. Still, static file is not loading.
EDIT2--I ran the command python manage.py findstatic web/img/target.jpg as mentioned here: https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#findstatic
It returned the file location on local machine but on heroku, it says 'No matching file found for 'web/img/target.jpg'.' Why is it not being located even after a collectstatic command has run successfully?
How does the production fetch of static files actually work? When I use {% static web/img/target.jpg %}, does it go to the STATIC_ROOT location to fetch it?
You have to serve the static file using nginx or you have to add path in urls py.
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
After doing 'find' on the remote heroku server from my machine, I came to know that the file is stored as 'target.JPG' and not 'target.jpg'.
I changed the access link accordingly in the template and it worked.
On the local machine, the CAPS do not seem to matter as I had already played around with them earlier.
Also, my git push to heroku never really changed the filename to 'target.jpg' because it doesn't consider changes in the caps of the filename unless told to as mentioned here - Changing capitalization of filenames in Git
Thank You.
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 know this question has been asked many times but even after resolving all the things I am still getting this error. My setup is as follow -
settings.py
"""
Django settings for my_notebook project.
Generated by 'django-admin startproject' using Django 1.8.3.
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
#outside src folder
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 = 'zzyo5*=sv3of&2la#$v=6)9x&+sn_b4sr94==mi1$b*&qhej+!'
# 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',
'signups'
)
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 = 'my_notebook.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 = 'my_notebook.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/'
#templates location
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "static_1", "templates"),
)
as its appearing in the error page.
I have a file defined in this folder signup.html
My view appears as -
from django.shortcuts import render, render_to_response, RequestContext
# Create your views here.
def home(request):
return render_to_response("signup.html", locals(), context_instance=RequestContext(request))
this view appears inside an app named signups which has been added to settings.py already in my project as -
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'signups'
)
Lastly urls.py of my project -
urlpatterns = patterns('',
url(r'^$', "signups.views.home", name='home'),
url(r'^admin/', include(admin.site.urls)),
)
Can someone please help me why i am getting this error
TemplateDoesNotExist at / signup.html
I am using django 1.8.3.
Thanks in advance
The TEMPLATE_DIRS setting should only be configured if you are loading templates that do not belong to any application.
In your case you have a template signup.html that is for the signups application; so you should do this:
First, get rid of the TEMPLATE_DIRS setting. In django 1.8 this setting was removed anyway (see this page on the new template configuration).
Create a directory called templates in the same directory that has the views.py for your signups app, it should look like this:
signups/
migrations/
__init__.py
admin.py
models.py
tests.py
views.py
templates/
signups/
In this signups/templates/signups/ directory, create your signup.html file.
Now, in your view you need:
from django.shortcuts import render
def home(request):
return render(request, 'signups/signup.html')