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')
Related
Problem: None of the changes I'm making to my CSS files are being applied to my HTML pages. And when I try and make new HTML/CSS files I get errors when I inspect the page in developer mode. The errors are saying they can't find my CSS files.
Exact error when I inspect my page in developer mode
GET http://127.0.0.1:8000/static/css/other.css net::ERR_ABORTED 404 (Not Found)
Background:
I'm creating a basic image editing site using django, html/css, and injecting JS to apply some filters to images. Previously I was able to make changes and they were reflected in the page, but now I can even delete my css file and it still uses an older version.
Things I've tried:
Gone into settings cleared browser cache
Disabled caching in developer mode
appended the version of css file ?v1.1 to force a rest (caused the 404 error from above)
Run collectstatic in terminal
Cleared cache opened site in private window
Watched several youtube vids on setting up static file dir and I think its correct. At some point in time my css was loading and updating as I made changes.
Directory Layout
These are my settings
Settings.py
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Image_API',
'rest_framework',
]
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 = 'Image_API.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
STATIC_URL = 'static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../static'),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), '../static')
Urls.py File
from django.contrib import admin
from django.urls import path
from Image_API import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
path('',views.upload2, name='upload'),
path('upload/', views.upload2, name='upload'),
path('other/', views.other),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root =settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
How my HMTL Files refrence css
I have load static at the top of the page and have my link to the css in the header tag.
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static '/css/style.css' %}">
It looks like the problem might be coming from your STATIC_URL setting and or STATIC_ROOT. Try changing it to:
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
You might also want to check that your urls.py file is setup correctly:
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Restart your server after making these changes just to be sure.
ps: collect static is run during deployment
You might have overlooked and updated CSS in /staticfiles/css/
Instead try updating it in /media/css.
staticfiles directory is auto-generated when you run python manage.py collectstatic.
You can try deleting staticfiles directory and run python manage.py collectstatic and see if it fixes the issue.
I have a problem using templates in django. I believe I have the template in the right spot and after looking at the path from the error log, the file is there. I also have it working without using render(). But I have tried multiple things and in the error log it shows a path that I can follow to the html file that I am trying to render.
Here is the file structure of my project (Note: this file structure is actually inside C:\my_website)
Relevant code:
Below is my view from the hello app I created. How it is currently there is an error but if I comment out the render() call and use the uncommented code It displays the contents of index.html
C:\my_website\my_website\hello\views
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
import os
import logging #MS ADDED
logger = logging.getLogger(__name__)#MS ADDED
def index(request):
#!!! It works with this stuff uncommented
#index_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello\\templates\\hello\\index.html')
#logger.error('Views - index_path is ' + index_path) # MS ADDED
#with open(index_path) as f:
# html_string = f.read()
#return HttpResponse(html_string)
return render(request, 'hello/index.hmtl')
Below is everything that I have changed in the settings. I read in the Django docs that if you didnt specify a path it would look in a templates directory in the app you create (hello). But leaving DIRS empty in TEMPLATES did gave a TemplateDoesNotExist exception. So I tried a few other things that did not work shown below.
C:\my_website\my_website\my_website\settings
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello.apps.HelloConfig',
]
SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__))#MS ADDED
Temp_Path = os.path.realpath('.')# MS ADDED
index_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello/templates')#MS ADDED
#MS Note: I tried for DIRS below os.path.join(SETTINGS_PATH,'templates')
#MS Note: I tried for DIRS below Temp_Path + "hello/templates"
#MS Note: I tried for DIRS Below os.path.join(os.path.dirname(os.path.dirname(__file__)),'hello/templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [index_path],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Below is the urls
C:\my_website\my_website\my_website
from django.contrib import admin
from django.urls import path
from hello import views
urlpatterns = [
path('',views.index,name='index'),
path('admin/', admin.site.urls),
#path('hello/', hello.views.index),
]
error log:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.2
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'hello.apps.HelloConfig']
Installed 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']
Template loader postmortem
Django tried loading these templates, in this order:
Using engine django:
* django.template.loaders.filesystem.Loader: C:\my_website\my_website\templates\hello\index.hmtl (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\my_website\env\lib\site-packages\django\contrib\admin\templates\hello\index.hmtl (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\my_website\env\lib\site-packages\django\contrib\auth\templates\hello\index.hmtl (Source does not exist)
* django.template.loaders.app_directories.Loader: C:\my_website\my_website\hello\templates\hello\index.hmtl (Source does not exist)
Traceback (most recent call last):
File "C:\my_website\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\my_website\env\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\my_website\my_website\hello\views.py", line 16, in index
return render(request, 'hello/index.hmtl')
File "C:\my_website\env\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\my_website\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string
template = get_template(template_name, using=using)
File "C:\my_website\env\lib\site-packages\django\template\loader.py", line 19, in get_template
raise TemplateDoesNotExist(template_name, chain=chain)
Exception Type: TemplateDoesNotExist at /
Exception Value: hello/index.hmtl
In the error log it says this
C:\my_website\my_website\hello\templates\hello\index.hmtl (Source does not exist)
But it does exist and it contains just
<h1>Hello World! aafa</h1>
With the commented out code in the view, the app displays:
I am using django version 3.1.2 and python version 3.8.6
any help would be greatly appreciated
In the render function you're passing "index.hmtl" instead of "index.html"
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.
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
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.