TemplateDoesNotExist at /polls/ - python

I have been trying out the Django tutorialDjango Tutorial Page 3 and encountered this error
"TemplateDoesNotExist at /polls/ " .
I assume the problem is with my code pointing the templates file index.html. This is my file structure for index.html: mysite/polls/templates/polls.
I am copying my settings.py and views.py here.
settings.py
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
views. Py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from polls.models import Poll
# Create your views here.
#def index(request):
#return HttpResponse("Hello, world. You are at the poll index.")
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_poll_list': latest_poll_list,
})
return HttpResponse(template.render(context))
def detail(request,poll_id):
return HttpResponse("You're looking at the results of the poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request,poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
Can someone look into it and help me to solve this error. Any help would be appreciated.
This is the traceback `Environment:
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls')
Installed Middleware:
('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')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Python34\mysite\templates\polls\index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\polls\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\polls\index.html (File does not exist)
C:\Python34\mysite\polls\templates\polls\index.html (File does not exist)
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\mysite\polls\views.py" in index
14. template = loader.get_template('polls/index.html')
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template
138. template, origin = find_template(template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in find_template
131. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /polls/
Exception Value: polls/index.html`
Please let me know if i missed out anything that would give a more clear picture. Thanks in advance.
Settings.py """
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ma_x5+pnvp$o7#5g#lb)0g$sa5ln%k(z#wcahwib4dngbbe9^='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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',
'polls',
)
MIDDLEWARE_CLASSES = (
'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'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'C://Python34/mysite/db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
#TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'

Whoa whoa whoa. Let's not advocate non re-usability of apps.
For templates that don't fit anywhere else (usually your base template, maybe some partial templates like form includes, etc.), it's fine to put them in your root templates directory (ie. /path/to/project/templates/base.html). You would refer to them in a view for rendering as base.html.
For other templates, I would advise you put them in the directory of the app that contains the views that render to those templates. For example, your polls index would go somewhere such as /path/to/project/polls/templates/polls/index.html.
The extra polls directory may look redundant there, but the reason is that the django template loader will (logically) dump all your templates in one directory. So we use the second polls directory to differentiate between multiple index.html templates that may exist. So in your view, you would use polls/index.html as normal.
The reason that this is a Good Thing is that it makes your apps more easily reusable. Written one polls app? You've written them all. If you do this, and also keep your app specific static files (js, css, images, etc.) in your app's static directory, and have a urls.py for each app, generally all you will need to do to move your app from one project to another is copy the directory, add to the new project's INSTALLED_APPS, and include the urls from your base urls.py. And of course, modify the app in any way you need to for the new project.
It also means if you're using an editor with sidebar navigation (most of them, these days), you don't have to scroll all the way down to your templates to find the template for that app. When you start working on large projects this gets tedious, fast.
The only thing to remember in using this technique is that you must have django.template.loaders.app_directories.Loader in your TEMPLATE_LOADERS setting. This is the default so you usually won't have to worry about it.
There is a nice guide for this in the django docs: https://docs.djangoproject.com/en/1.7/intro/reusable-apps/
To answer the question you actually asked:
Your index.html should be here: C:\Python34\mysite\polls\templates\polls\index.html. If it isn't, that's what you're doing wrong.
On a related note, you probably shouldn't have your project in the Python directory.

Try to put template folder in projects root folder:
mysite/templates/polls/index.html
Explanation
Your template dirs is
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
It containts only one directory: /path/to/your/project/templates
And your index.html located in /path/to/your/project/polls/templates
Update
As you say it doesn't work with templates stored in mysite/templates/polls/index.html let's try this way:
go to mysite and run
python manage.py shell
to run interactive interpreter with mysite as context. Then run this:
from settings import TEMPLATE_DIRS
print TEMPLATE_DIRS
it will output something like
('/var/www/mithril/templates/', '/home/dmitry/proj/mithril/templates/')
Django uses this directories to find your templates.
Thus you should put directory polls/ in folder from TEMPLATE_DIRS.

You forgot to add your app config in the INSTALLED_APP in settings.py
INSTALLED_APPS = (
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
The startapp command creates an apps.py file. Since it doesn’t use default_app_config (a
discouraged API), you must specify the app config’s path, e.g. 'polls.apps.PollsConfig', in
INSTALLED_APPS for it to be used (instead of just 'polls').

I was having the same problem and I noticed there was another HTML file named index in site-packages. So I just changed my current HTML file to index1 and it worked.

Try to replace:
template = loader.get_template('polls/index.html')
with this:
template = loader.get_template('index.html')

Check if you forgot the 's' in
/polls/template
its
'/polls/templates' folder.

In your settings.py file, add this
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
And then in TEMPLATES DIRS, add this,
TEMPLATES = [
{
...
'DIRS': [TEMPLATE_DIR,],
...
},]

The issue is with your folder structure. Since you are inside the polls folder, you should have this template = loader.get_template('index.html') instead of template = loader.get_template('polls/index.html')
This is because of how the python path works, see here OS Path

You follow this structure,
mysite/
mysite/
templates/
polls/
index.html
there's something suspect to your TEMPLATE_DIRS path. It should point to the root of your template directory.
import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
In your error log django searching these paths,
C:\Python34\mysite\templates\polls\index.html
C:\Python34\mysite\polls\templates\polls\index.html

Make sure you didn't misspell detail.html as details.html. This was my problem.

you should have placed your templates inside poll app inside templates/polls/ structured. Such that the full path will look like mysite/polls/templates/polls/file.html

I had the same issue running through the tutorial. None of the above answers worked for me.
my solution:
make sure when you are saving your html files, click SAVE AS and then click the file type and click "All Files". My index.html file was actually index.html.txt and was not being found.

Related

"TemplateDoesNotExist at /my_app_name" but Template-loader postmortem says "(File exists)"

I am getting the following error:
TemplateDoesNotExist at /app1/1/about/
index/index.html
but Template-loader postmortem says:
/var/www/web/sites/mysite.com/app1/templates/index/index.html (File exists)
I have tried all stackoverflow's answers on similar questions, but they didn't work for me. On my local server(running on OSX, virtualenv) everything is alright, but on production server I'm getting this error. On production server I'm using Django 1.7.5 on Ubuntu 14 with virtualenv.
Each app has it`s own template, the structure is like this:
app1
--templates
----index
------index.html
------head.html views.py app2
--templates
----index
------index.html
------head.html views.py
In settings.py I have the following parameters for templates:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DEBUG = True
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'),]
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
INSTALLED_APPS = (
# django
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# widgets
'widget_tweaks',
'compressor',
'tinymce',
'django_activeurl',
'debug_toolbar',
# modules
'app1',
'app2',
)
and including them in views like this:
template_event = loader.get_template('index/materials.html', dirs=["app1/templates/"])
You have confused the template loader by passing in the dirs argument, which overrides whatever is in TEMPLATE_DIRS.
First, you don't need to set TEMPLATE_DIRS if all your templates are included inside app directories. The TEMPLATE_DIRS variable exists if you want to load templates from other file system locations. If all your templates are in app/templates/, then you don't need to set TEMPLATE_DIRS.
Since you are trying to load a template that is part of an application, simply pass the relative path to the template:
template_event = loader.get_template('index/materials.html')
Now, here is what django is gong to do (highly simplified):
First, it will look at TEMPLATE_LOADERS and then call each of the loader for its templates. The first loader is the file system loader, which will use the TEMPLATE_DIRS setting to find any templates. If a template here matches the path, then it will stop.
The next loader is the app_directories loader, this loader will look for a directory named templates in any app that is added to INSTALLED_APPS and then return the first template that matches.
The postmartem is telling you that the loaders have found your template, but the way you are asking them to load templates - they cannot find the template.
Just realized my mistake, after deep reading of django documentation, figured out that Alsadair was right with his answer in comments.
Usually, the recommendation is to put an app1 subdirectory i.e.
app1/templates/app1/, and load app1/index/materials.html. Then dirs is
unnecessary, in load_templates, and the template should be loaded from
the correct directory.

Django: TemplateDoesNotExist. Tried numerous different things already

I know this is a common issue apparently, but I've gone through a bunch of examples and can't find a solution.
I'm doing the tutorial of django1.8. so I'm not sure if this is a glitch or not. I've tried moving my template file to multiple locations, but so far nothing has worked.
I have my project structured in this way: my project is called "forumtest" and it's inside a virtualenv called "venv". Forumtest has one app called "polls". I had the "templates" folder stored inside the root directory of "forumtest", but I just moved it inside the "polls" directory. However, I got the same result.
As of now, my settings.py file looks like this:
"""
Django settings for forumtest 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
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 = '$nnwkm0ln!$77m1n!%wv-5)k_rhs=-p-)xr-c-+m985w3jq#*='
# 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',
'polls',
)
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 = 'forumtest.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join (BASE_DIR,'C:/Desktop/Users/Owner/forumtest/polls/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 = 'forumtest.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'forumtest',
'USER': 'admin',
'PASSWORD': 'aldotheapache12',
'HOST': 'localhost',
'PORT': '',
}
}
# 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/'
The 'DIRS' section which looks like this:
'DIRS': [os.path.join (BASE_DIR,'C:/Desktop/Users/Owner/forumtest/polls/templates')],
Previously looked like this:
'DIRS': [os.path.join (BASE_DIR,'templates')],
My views file, stored under the "forumtest" directory looks like this:
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from polls.models import Choice,Question
# Create your views here.
class IndexView(generic.ListView):
template_name = 'index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions"""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request,question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except(KeyError,Choice.DoesNotExist):
#redisplay the question voting form
return render(request,'polls/detail.html',{
'question':p,
'error_message': "you didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
I have the exact same views file under "polls", except with this line (I'm aware that this may be an issue:
from .models import Choice,Question
Please let me know how I can solve this. Thanks guys!
EDIT: as per requested by #Chris McGinlay, here's the template loader post-mortem:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Users\Owner\Desktop\venv\forumtest\templates\index.html, polls\question_list.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Users\Owner\Desktop\venv\lib\site-packages\django\contrib\admin\templates\index.html, polls\question_list.html (File does not exist)
C:\Users\Owner\Desktop\venv\lib\site-packages\django\contrib\auth\templates\index.html, polls\question_list.html (File does not exist)
C:\Users\Owner\Desktop\venv\forumtest\polls\templates\index.html, polls\question_list.html (File does not exist)
Thanks for all your comments, guys!
EDIT: So I deleted the extra views file located under the 'forumtest/forumtest' directory, and now I'm getting an error that says
cannot import name 'views'
:(
EDIT: #Alasdair here's the root urls.py file:
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
# ex: /polls/
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^polls/', include('polls.urls',namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
]
I think that the templates DIRS in the TEMPLATES setting should be as it was:
'DIRS': [os.path.join (BASE_DIR,'templates')],
Having 'APP_DIRS': True, should pull in the templates from all your apps.
When you obtain the dreaded 'TemplateDoesNotExist at ...' message in your browser, it will probably help to look down to the Template Loader post-mortem:
Django tried loading these templates, in this order:
Hopefully that will give some clues - could you post it here?
You shouldn't have to include the polls directory in your DIRS setting. Django will find it because you have APP_DIRS set to True.
So you can change DIRS back to.
'DIRS': [os.path.join(BASE_DIR,'templates')],
Now, note that there should be a polls directory inside polls/templates for example the details template should be at polls/templates/polls/details.html.
Finally, stick with the tutorial, and keep the polls views in polls/views.py. Having two similar files forumtest/views.py and polls/views.py is going to make things very confusing.
Had the same problem, open that file in finder or outside the text editor/IDE and rename it, also check the extension.
Try this:
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
INSTALLED_APPS = (
...
'polls',
)
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
with this your templates should be inside "polls/templates" directory or in the main "templates" directory

Django 1.6: How to access static files in view

I've already tried the solution here and it didn't work for me. I'm creating a project based off the Heroku "Getting Started" project for Python.
In views.py, I'd like to be able to access a file in the static/data/ folder. However, most of my attempts I make to create the correct url to the file have failed. The only thing that works is putting the absolute path to the file as it exists on my local file system, which obviously won't work when I deploy my app.
Previous attempts to open the file include:
from django.templatetags.static import static
url = static('data/foobar.csv')
os.path.isfile(url) # False
from django.conf import settings
url = os.path.join(settings.STATIC_URL, 'data/foobar.csv')
os.path.isfile(url) # False
Here is my directory structure:
/appname
/app
/templates
views.py
/appname
/static
/js
/css
/data
settings.py
urls.py
settings.py:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
)
MIDDLEWARE_CLASSES = (
'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 = 'appname.urls'
WSGI_APPLICATION = 'appname.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Instead of joining the STATIC_ROOT with the filename, use the staticfiles_storage interface instead. This will also work with remote static files like S3/django-storages.
from django.contrib.staticfiles.storage import staticfiles_storage
url = staticfiles_storage.url('data/foobar.csv')
With staticfiles_storage you can also do simple file operations like open, delete, save.
The particular staticfiles storage backend you've configured will provide both a path method and a url method.
from django.contrib.staticfiles.storage import staticfiles_storage
p = staticfiles_storage.path('data/foobar.csv')
content = p.readlines()
# manipulate content
The .url method returns the same value as Django's static built-in
url = static('data/foobar.csv')
When you deploy a Django application to Heroku, or when you manually run manage.py collectstatic task, all the static assets will be copied to your STATIC_ROOT directory. Therefore you should use:
file_path = os.path.join(settings.STATIC_ROOT, 'data/foobar.csv')
STATIC_ROOT = 'staticfiles' is your problem. From the docs, STATIC_ROOT is:
The absolute path to the directory where collectstatic will collect static files for deployment.
Currently, you don't even have a path listed there...
Your static files are not at the same place when you are in "dev" or "prod".
In dev, you use the django "runserver" command which will serve your static file with "original" files (eg : myproject/src/appname/static/appname/images/plop.jpeg)
In production mode, you must use the "collectstatic" django command which will copy those original file in a "direct public http access folder" (eg : /static/appname/images/plop.jpeg for an http access)
But original files are still at the same place (myproject/src/appname/static/appname/images/plop.jpeg), so your view can access those original file directly.
If you know in which app the file your are looking for is, it is very simple. If you want to use the "static overwrite" mecanims of Django, have a look to its functions to get the "final" static file (for exemple, is it myproject/python-env/lib/python2.7/site-packages/coolapp/static/coolapp/images/plop.jpeg or myproject/src/myapp/static/coolapp/images/plop.jpeg)
I recommend to read the Django Doc about static finders to better understand how it works : https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_FINDERS
PS : "HTTP path" and "python path" are not the same ;)
Just had the same problem. Don't know if this is the best solution.
In settings.py I created two paths for switching between productive and development. I need to uncomment when deploying the site.
#Productive
#STATIC_ROOT = '/home/DimiDev/RESite/static'
#Development
STATIC_ROOT = 'realestate/static'
And in my python file, as already stated in this post.
from django.contrib.staticfiles.storage import staticfiles_storage
file_path = staticfiles_storage.path('realestate/ml/2xgBoosting_max.sav')
My structure for this file:
RESite\realestate\static\realestate\ml\2xgBoosting_max.sav
Let me tell you what I did, I made an app in which I had to read a CSV file.
I made the main project directory with django-startproject command and then made an app.
In the root I made a folder named static and inside that, I placed the CSV file.
Now in my views.py
read_csv('static/file_name')
All other settings were default and this worked for me!
What you are trying to do can be achieved the following way.
First as your settings.py file has this base path:
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
You can get files in your static directory this way:
url = os.path.join(settings.BASE_DIR, 'static/data/foobar.csv')
os.path.isfile(url) # True

Django can't find templates, file exists and specified TEMPLATE_DIR

I know there are lots of these questions already but I haven't been able to find an answer. I'm trying to get my homepage to load but I have been getting this error:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.7.1
Exception Type: TemplateDoesNotExist
Exception Value:
base.html
Exception Location: /Users/user/.virtualenvs/screen_savers/lib/python3.4/site-packages/django/template/loader.py in find_template, line 136
Python Executable: /Users/user/.virtualenvs/screen_savers/bin/python
Python Version: 3.4.1
Python Path:
['/Users/user/Devspace/scren_savers/the_screen_savers',
'/Users/user/.virtualenvs/screen_savers/lib/python34.zip',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4/plat-darwin',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4',
'/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4/site-packages']
and can't seem to figure out why. I specified my TEMPLATE_DIR properly in my settings.py and made sure that the file exists where is says it does. I have also looked through all of these questions where people had the same problem but none of them solved my problem:
Django App template Loader, can't find app templates
Django template Path
Django can't find template
Django TemplateDoesNotExist?
Template does not exist
Django cant find templates
What really confuses me is that if I check the value of BASE_DIR and TEMPLATE_DIR it gives me:
/Users/user/Devspace/scren_savers/the_screen_savers
/Users/user/Devspace/scren_savers/the_screen_savers/templates
respectively which is exactly what I expect to see. It seems like it knows where the templates are but still can't see them. Any help would be greatly appreciated.
Also an additional, less important question:
I have seen BASE_DIR + '/templates' and os.path.join(BASE_DIR, "templates") suggested as the proper way to specify the TEMPLATE_DIR. Is one of these better than the other (if so why) or is this just a matter of personal preference?
Here is the view that I am trying to load:
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
class home_page(View):
def get(self, request):
return render(request, 'base.html')
and here is my settings file:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIR = (
BASE_DIR + "/templates/",
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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',
'screen_savers',
)
MIDDLEWARE_CLASSES = (
'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 = 'screen_savers.urls'
WSGI_APPLICATION = 'screen_savers.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/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.6/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.6/howto/static-files/
STATIC_URL = '/static/'
You should change in file settings.py TEMPLATE_DIR to TEMPLATE_DIRS.

template not found for Django homepage

I'm still new to Django and I am trying to create a small website as practice. However I am currently running into this error. If someone could explain where I went wrong and teach me how I can fix this that would be great! I'm new and the Documentation can be hard to read sometimes =[
Please let me know if there is anything else I need to add!
Environment:
Request Method: GET
Request URL: http://localhost:8000/home/
Django Version: 1.5.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/bradford/Development/Django/pub_pic/~/Development/Django/pub_pic/templates/homepage_template/home.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/contrib/auth/templates/homepage_template/home.html (File does not exist)
Traceback:
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/bradford/Development/Django/pub_pic/homepage/views.py" in index
9. return render(request,'homepage_template/home.html')
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/shortcuts/__init__.py" in render
53. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
170. t = get_template(template_name)
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/template/loader.py" in get_template
146. template, origin = find_template(template_name)
File "/home/bradford/Development/Django/django_1.5.1/local/lib/python2.7/site-packages/django/template/loader.py" in find_template
139. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /home/
Exception Value: homepage_template/home.html
I have a template named home.html and it is in the directory pub_pic/templates/homepage_template/home.html
My pub_pic urls.py:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'home/',include('homepage.urls', namespace = 'home')),
)
My homepage urls.py:
from django.conf.urls import patterns, url
from homepage import views
urlpatterns = patterns('',
url(r'^$', views.index, name = 'index'),
)
homepage/views.py:
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render, render_to_response
#from homepage.models import
def index(request):
# template = loader.get_template('homepage/index.html')
return render(request,'homepage_template/home.html')
Please do not include the full path in settings as the accepted answer suggests. This is the "anti-django" way of doing things, even if it does work.
In Django you can either have one templates folder for a project or one templates folder per app. The latter allows you to move apps from project to project (which is how they are supposed to work) but the former can provide simplicity for monolithic once-off projects.
You DO NOT need to and should not specify the absolute path. In your settings, if you want a single templates directory for your project use something like:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates')
,)
This is basically saying your templates are in a folder called 'templates' that is in the main BASE_DIR path. In this example that would be the root directory where the manage.py resides. Now just make a folder called 'templates' in this root directory and throw your HTML in there (arranged in subfolders if you like).
Templates can then be loaded as simply as
templt = get_template('mytemplate.html)
Where it is presumed that mytemplate.html file resides directly in the templates/ folder off the root directory. You can use subfolders and if you do you should specify them in the quotes e.g. 'mysubdir/mytemplate.html'
As an alternative, you can allow each app to have its own templates
In this case you must have the following in settings:
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',
],
},
},
]
The key here is
'APP_DIRS': True,
This (according to the Django docs) instructs the system to look in each app for a 'templates' folder. Your project would then look something like (presuming a project name of mybigproject)
/home/myaccount/mybigproject/myapp1/templates/
and
/home/myaccount/mybigproject/myapp2/templates/
By contrast in the first scenario (single templates folder) it would just be
/home/myaccount/mybigproject/templates/
However the important thing to take away is that you STILL REFERENCE IT AS:
templt = get_template('mytemplate.html)
Django will search through all the app folders for you.
If it still gives you a file not found error it is a configuration thing.
If you specify a full path, now you need to change that path as you move PC's (e.g. shared projects), projects or apps which is a disaster.
In your settings.py file you should use below code.
#settings.py
import os
# Full filesystem path to the project.
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),)
You don't show the value of your TEMPLATE_DIRS setting. But looking at the error message, it looks like you're using ~/... there. Don't do that: use the full path - /home/bradford/Development/Django/pub_pic/templates.
Installed Applications:
('homepage_template.apps.Homepage_templateConfig', #add this line
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles')

Categories

Resources