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"
Related
I am trying to work with Django REST framework but I am getting the AttributeError at /
'OrderedDict' object has no attribute 'register'.
I think I have followed the documentation properly Can someone help with this.
Link to the tutorial: https://www.django-rest-framework.org/tutorial/quickstart/
I have already used Django now I am trying to work with the Django REST framework but following the quickstart tutorial is resulting in:
AttributeError at /
'OrderedDict' object has no attribute 'register'.
tutorial.py/urls.py
from rest_framework import routers
from quickstart import views
from django.contrib import admin
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
tutorial/quickstart/serializers.py
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['url', 'username', 'email', 'groups']
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ['url', 'name']
tutorial/quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
tutorial/settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&m8r-k(#%7tw6u31r-83ld_3#uw+86xrztepov4&=+s(&uapy2'
# 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',
'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 = 'tutorial.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 = 'tutorial.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
The error response is :
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.2.3
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework']
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']
Traceback:
File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\base.py" in _get_response
145. response = self.process_exception_by_middleware(e, request)
File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\base.py" in _get_response
143. response = response.render()
File "D:\ProgrammingFiles\lib\site-packages\django\template\response.py" in render
106. self.content = self.rendered_content
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\response.py" in rendered_content
70. ret = renderer.render(self.data, accepted_media_type, context)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\renderers.py" in render
725. context = self.get_context(data, accepted_media_type, renderer_context)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\renderers.py" in get_context
687. 'description': self.get_description(view, response.status_code),
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\renderers.py" in get_description
602. return view.get_view_description(html=True)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\views.py" in get_view_description
245. return func(self, html)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\views.py" in get_view_description
61. return formatting.markup_description(description)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\utils\formatting.py" in markup_description
63. description = apply_markdown(description)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\compat.py" in apply_markdown
156. md_filter_add_syntax_highlight(md)
File "D:\ProgrammingFiles\lib\site-packages\rest_framework\compat.py" in md_filter_add_syntax_highlight
213. md.preprocessors.register(CodeBlockPreprocessor(), 'highlight', 40)
Exception Type: AttributeError at /
Exception Value: 'OrderedDict' object has no attribute 'register'
The result should be :
https://www.django-rest-framework.org/img/quickstart.png
The version of the markdown library you have installed is incompatible with the version of Django REST Framework you are using.
Update the markdown library to at least 3.0 to fix this issue.
Edit: As mentioned in the comments, if you have markdown 3.1 installed, your Python interpreter probably picks up an older version that is installed somewhere else.
You can check which version of markdown your interpreter picks up, by importing it and inspecting markdown.__file__ and markdown.version.
The most reliable way is probably to add these lines to your settings.py:
import markdown
print('Markdown module path', markdown.__file__)
print('Markdown version:', markdown.version)
How to get rid of the old module depends on how it got installed in the first place.
The preferred way to avoid these kinds of conflicts is using a virtual environment (or short virtualenv).
The tutorial you linked to uses a virtual environment, so if you followed it step by step, you should not have this problem. Maybe you simply forgot to activate the virtualenv?
Linux/Mac: source env/bin/activate
Windows: env\Scripts\activate
I found this solution works for me
pip install git+https://github.com/Python-Markdown/markdown.git
I have the same issue, but poetry does not allow me to update Markdown to from 2.6.11 to 3+ because apache-airflow (1.10.10) depends on markdown (>=2.5.2,<3.0)
I successfully used this workaround declared in settings.py:
from rest_framework import compat
compat.md_filter_add_syntax_highlight = lambda md: False
Thanks a lot to this redditer
It was because of the version of Markdown my project was importing.
As my global Markdown version was 3.1
but when I am checking it in the project after debugging it is still in version 2.
Creating a virtual env was the solution for this.
Thank you.
I was trying to create a blog in my domain using django 1.9 and python 3.5 with virtual environment. So while deploying on pythonanywhere. I am able to render the html. Here is the traceback.
Request Method: GET
Request URL: http://www.example.com/
Django Version: 1.9
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin', `
` 'django.contrib.auth', `
`'django.contrib.contenttypes',`
`'django.contrib.sessions',`
`'django.contrib.messages',`
`'django.contrib.staticfiles',`
`'blog']``
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.auth.middleware.SessionAuthenticationMiddleware',
'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.app_directories.Loader:
/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/admin/templates/blog/templates/blog/post/list.html(Source does not exist)
* django.template.loaders.app_directories.Loader:
/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/auth/templates/blog/templates/blog/post/list.html(Source does not exist)
* django.template.loaders.app_directories.Loader:
/home/pdlsaroj22/myblog/mysite/blog/templates/blog/templates/blog/post/list.html (Source does not exist)
Using engine django:
* django.template.loaders.app_directories.Loader:
/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/admin/templates/blog/post_list.html (Source does not exist)
* django.template.loaders.app_directories.Loader:
/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/contrib/auth/templates/blog/post_list.html (Source does not exist)
* django.template.loaders.app_directories.Loader:
/home/pdlsaroj22/myblog/mysite/blog/templates/blog/post_list.html (Source does not exist)
Traceback:
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
response = `self.process_exception_by_middleware(e, request)
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
response = response.render()
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in render
self.content = self.rendered_content
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in rendered_content
template = self._resolve_template(self.template_name)
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in _resolve_template
new_template = self.resolve_template(template)
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/response.py" in resolve_template
return select_template(template, using=self.using)
File "/home/pdlsaroj22/.virtualenvs/venv/lib/python3.5/site-packages/django/template/loader.py" in select_template
raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
Exception Type: TemplateDoesNotExist at /
Exception Value: blog/templates/blog/post/list.html, blog/post_list.html
My views.py looks like this:
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/templates/blog/post/list.html'
If u have an app called blog (As registered in your settings.py), and you have APP_DIR set to true under template directories in settings.py, then chances are that you have a directory called templates in your blog app and another directory called blog within templates.
If that is the case, then blog/templates/blog/post/list.html should actually be written as: post/list.html provided you have a post directory in the blog directory of the blog app.
you have to make folder named "templates" where settingd.py reside, and put your .html file in this template folder. and make changes in following settings.py file:
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',
],
},
},
]
And in your code do changes as following:
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'list.html'
hope this answer help you.
I'm adding text content to a webapp.
When I ran the app in the local server i had no issue, but when i uploaded the template to the server it returns me this error:
Environment:
Request Method: GET
Request URL: http://www.centros-sbc.com/domiciliaciones
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',
'django.contrib.humanize',
'suit',
'django.contrib.admin',
'sbcweb',
'south',
'compressor',
'django.contrib.sitemaps',
'captcha')
Installed Middleware:
('django.middleware.cache.UpdateCacheMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware')
Template Loader Error:
Django tried loading these templates, in this order:
**Using loader django.template.loaders.filesystem.Loader: **
**/home/manager/webs/sbc-web/sbcweb/templates/general/domiciliaciones.html (File exists)**
Using loader django.template.loaders.app_directories.Loader:
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/general/domiciliaciones.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/suit/templates/general/domiciliaciones.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/general/domiciliaciones.html (File does not exist)
**/home/manager/webs/sbc-web/sbcweb/templates/general/domiciliaciones.html (File exists)**
/usr/local/lib/python2.7/dist-packages/compressor/templates/general/domiciliaciones.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/sitemaps/templates/general/domiciliaciones.html (File does not exist)
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/home/manager/webs/sbc-web/sbcweb/views/general.py" in domiciliaciones
27. return render_to_response('general/domiciliaciones.html', response, context_instance=RequestContext(request))
File "/usr/local/lib/python2.7/dist-packages/django/shortcuts/__init__.py" in render_to_response
29. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in render_to_string
170. t = get_template(template_name)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in get_template
146. template, origin = find_template(template_name)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in find_template
139. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /domiciliaciones
Exception Value: general/domiciliaciones.html
here are my template loaders:
TEMPLATE_LOADERS = (
#'django_mobile.loader.Loader',
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#'django.template.loaders.eggs.Loader',
)
My template dirs:
TEMPLATE_DIRS = (
os.path.join(APP_PATH, "templates"),
)
the app path:
APP_PATH = os.path.dirname(os.path.abspath(__file__))
Here's the thing.
I just did few modifications on the text of /domiciliaciones.html processed the .po translation files and overwritted the translation files and the .html
I tried to fix the page returning to the original (without my changes) but it doesn't work neither.
If someone could help it would be great, I'm kind of desperate to fix that.
I don't know if you need more information about the app, just let me know!
Many thanks in advance!
Maybe I can answer your question! In Django 1.8.2, Deprecated since version 1.8: Set the DIRS option of a DjangoTemplates backend instead.,so,you should not set TEMPLATE_DIRS,In my opintion,you should set
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
}
]
I spent a half of day to solve this problem in my WebApp! I guess this will help you!
I am doing a tutorial about django project.
Actually it is 4.51 in the morning and i want to just make it work.
My urls.py file:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^polls/$', 'polls.views.index'),
)
My views.py file:
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render_to_response
def index(request):
return render_to_response('index.html')
In the folder templates I have index.html file.
It showed me the same TemplateDoesNotExist error, so I did some research and
I found this question
so I've added to my settings.py this code:
import os.path
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates/'),
)
So how to make it work??
This is the traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Django Version: 1.6.1
Python Version: 3.3.3
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:\Users\JD\PycharmProjects\MyDjangoApp\MyDjangoApp\templates\index.html
(File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python33\lib\site-packages\django\contrib\admin\templates\index.html
(File does not exist)
C:\Python33\lib\site-packages\django\contrib\auth\templates\index.html
(File does not exist)
Traceback:
File "C:\Python33\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\JD\PycharmProjects\MyDjangoApp\polls\views.py" in index
8. return render_to_response('index.html')
File "C:\Python33\lib\site-packages\django\shortcuts\__init__.py" in render_to_response
29. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "C:\Python33\lib\site-packages\django\template\loader.py" in render_to_string
162. t = get_template(template_name)
File "C:\Python33\lib\site-packages\django\template\loader.py" in get_template
138. template, origin = find_template(template_name)
File "C:\Python33\lib\site-packages\django\template\loader.py" in find_template
131. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /polls/
Exception Value: index.html
Change
import os.path
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
to
import os
SITE_ROOT = os.path.dirname(os.path.dirname(__file__))
If you look at your traceback, Python is looking for a template folder within your app folder, I assume that it would be the same folder as settings.py.
Another approach is to copy your templates folder into MyDjangoAPP folder.
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')