Django: TemplateDoesNotExist. Tried numerous different things already - python

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

Related

TemplateDoesNotExist at / learning_logs/index.html

Im following a tutorial about Django and I got this error and I dont know why its happening since Im following a book tutorial, I didnt have any error until now and I checked every piece of code, maybe its because Im using a new versio of Django?
This is 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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'REDACTED'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
# My apps
'learning_logs',
# Default django apps.
'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 = 'learning_log.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 = 'learning_log.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.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/3.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/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
This is views
from django.shortcuts import render
# Create your views here.
def index(request):
"""The home page for Learning Log."""
return render(request, 'learning_logs/index.html')
This is urls
"""Defines URL patterns for learning_logs."""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# Home page
path('', views.index, name='index')
I just followed every step in the book and the folders paths for the projects so why I have this problem?
The answer was the html files were not actually html instead they were .txt
I faced a similar issue but my error was that I forgot to make another learning_logs folder inside the templates folder.
Another error was that I did not create an html file but a text file for 'index.html'.
Download a sample html file from online (https://filesamples.com/formats/html) and rename it to just "index" and edit it to include the content shown in the book.
step 1:
for urls.py
from django.urls import path
from . import views
app_name = "learning_logs"
urlpatterns = [
path('', views.index, name = 'index'),
]
step 2:
for views.py
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request, 'index.html')
step 3:
Make a templates folder inside learning_logs app then, make a index.html folder inside templates folder......that's all.
Note: try this step.. this problem will be solve.

Django 404 error ('Page not found') after runserver

My project is named 'pages', and when I runserver I get this error. Anybody have any clue how to fix this error.
Page not found (404)
Request Method: GET Request URL: http://127.0.0.1:8000/ Using the
URLconf defined in pages_project.urls, Django tried these URL
patterns, in this order: admin/ The empty path didn't match any of
these. You're seeing this error because you have DEBUG = True in your
Django settings file. Change that to False, and Django will display a
standard 404 page.
My settings.py file looks like this:
"""
Django settings for pages_project project.
Generated by 'django-admin startproject' using Django 2.0.7.
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 = '*u)%-zmf=2g-c*3z2-&=n=asty5v36n62^90_u*-#83!wb=)eq'
# 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',
'pages', # new
]
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 = 'pages_project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pages_project.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'),
}
}
And my urls.py in my 'pages' folder is
from django.urls import path
from . import views
urlpatterns = [
path(' ', views.HomePageView.as_view(), name='home'),
]
Any help would be greatly appreciated. Thanks.
The error is telling you that the main urls.py only includes the admin pattern. You also need to include the pages urls.
Also, you have a space in your path pattern. Remove it.
You have a space in your path; ' '. This would mean that the url is http://127.0.0.1:8000/%20. Delete the space.
path('', views.HomePageView.as_view(), name='home')
You project urls: Remove the space
pages/urls.py
urlpatterns = [
path(r'^$', views.HomePageView.as_view(), name='home'),
]
Add your app urls at your project urls so that way your project can see your app url
projectName/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.views.static import serve
urlpatterns = [
...
url(r'^', include('pages.urls')),
]

Django settings and view mapping error

I have build a realtime notification app using Django(1.8.5). I am using django server, Nodejs as push server, ishout.js[nodejs+redis +express.js API]. So I installed them by following the instructions.
Kindly suggest how this error can be fixed :
settings.py file
"""
#Django settings for realtimenotif project.
Generated by 'django-admin startproject' using Django 1.8.5.
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 = 'gvvs-0*-cohfbm#()*nyt&0u!77sc_8vnw%1afpkmhi&y-6&ds'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ADMINS = (
#'arunsingh','arunsingh.in#gmail.com'
)
MANAGERS = ADMINS
ALLOWED_HOSTS = ["*"]
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'drealtime',
'sendnotif',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'drealtime.middleware.iShoutCookieMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'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 = 'realtimenotif.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'debug':DEBUG,
'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 = 'realtimenotif.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'),
#The following settings are not used with sqlite3:
'USER':'',
'PASSWORD':'',
'HOST':'', # Empty for localhost through domain sockets,127.0.0.1
'PORT':'', # Set to empty string for default
}
}
# 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/'
urls.py file
"""realtimenotif URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import patterns, include, url
#from sendnotif.views import home, alert
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(['',
url(r'^$', 'sendnotif.views.home', name='home'),
#url(r'^$', home, name='home'),
url(r'^alert/$', 'sendnotif.views.alert', name='alert'),
#url(r'^alert/$', alert, name='alert'),
url(r'^accounts/login/$','django.contrib.auth.views.login',name='login'),
#uncomment the next line to enable the admin:
url(r'^admin/$', include(admin.site.urls)),
] )
Django server is starting, it says works and gives this message
"You're seeing this message because you have DEBUG = True in your
Django settings file and you haven't configured any URLs. Get to
work!"
What changes I have to make in my settings.py and views.py file, Kindly suggest pointers to workaround. I have gone through official django documentation and beginner tutorials, but to no rescue.
You can see the project source code at githubRepo
Django fails to find your urls.py file.
You need to point the root URLconf at the realtimenotif.urls module. Create a top level urls.py and use an include(), eg:
yoursite/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^/', include('realtimenotif.urls')),
url(r'^admin/', include(admin.site.urls)),
]
or alternatively move your urls.py from realtimenotif to the top level folder.

css not loading in my login and admin page in django

I'm newbie in django and I started learning django with official tutorial.
I use django beside virtualenv, but I have a problem with
the login page and admin page because
they aren't load css and show login
page and admin page without any style
"""
Django settings for mysite 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 = 'g8%o#ackd!hzekoho4rn7r7-t_m!sk$*nwi-4j556t=!ln3(#+'
# 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 = 'mysite.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 = 'mysite.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/'
First of all, Create folder named as "static", then you need to copy all the css/js file into static folder inside your project(or wherever you create static folder). Then declare the static files directory path in your settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = ('assets', BASE_DIR +'/static/',)
In your html file, add following line - {% load staticfiles %} at top of the header section or top of the file.
In <head> section you can link the css/js file using following code
<link rel="stylesheet" href="{% static 'assets/css/mystyle.css'%}">
</link>
<script src="{% static 'assets/js/jquery.js'%}"></script>
You need to read through the documentation for serving static files. When you are in production, your webserver (nginx/apache) would be responsible for serving static files such as JS, CSS and images. So any request for an image or JS file would be taken care of immediately by the webserver while any request for an actual page would be passed to your application server (i.e. Django)
In development you need to tell the development server to actually serve your static files so you need to add the following to your root urls.py file:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
There are two situations that you maybe fail to load CSS files.
login Interceptor catch all the request, including your static files
browser cannot access your CSS files.
It is easy to judge what situation you are in. You can open your browser and check whether your CSS request is received. (for example, open your Chrome by F12 and check Console).
If there is not an error about failing to receive. Maybe your login Interceptor has caught all the things. And then, you can dig into what you received, at that you will find the answer. on my case, I find the response is my login page, not my ccs file.
You should let them go like this.
if static('') in request.path:
return self.get_response(request)
If received, you can see other answers.
(My English is not very good. If you want, you can edit this answer.)

TemplateDoesNotExist at /polls/

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.

Categories

Resources