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.
Related
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 modifying Gitstack, a 32bit Python2.7-based Git Web Application (available here) for my 64bit Python installation.
In the process, I also had to modify all the Django codes e.g. urlpatterns, etc.
While I managed to adapt it to my Apache/PHP environment, I ended up with this Django issue.
The error is as below while trying to access /gitstack location
TypeError at /registration/login/
sequence item 0: expected string or Unicode, function found
Request Method: GET
Request URL: https://localhost/registration/login/?next=/gitstack/
Django Version: 1.11.6
Exception Type: TypeError
Exception Value:
sequence item 0: expected string or Unicode, function found'
I could not make any useful insight from the traceback below with my little head. The traceback just ends inside Django which seems very little helpful.
Environment:
Request Method: GET
Request URL: https://localhost/registration/login/?next=/gitstack/
Django Version: 1.11.6
Python Version: 2.7.13
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'gitstack')
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')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner
41. response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response
249. response = self._get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response
172. resolver_match = resolver.resolve(request.path_info)
File "C:\Python27\lib\site-packages\django\urls\resolvers.py" in resolve
366. sub_match = pattern.resolve(new_path)
File "C:\Python27\lib\site-packages\django\urls\resolvers.py" in resolve
201. return ResolverMatch(self.callback, args, kwargs, self.name)
File "C:\Python27\lib\site-packages\django\urls\resolvers.py" in __init__
55. self.view_name = ':'.join(self.namespaces + [view_path])
Exception Type: TypeError at /registration/login/
Exception Value: sequence item 0: expected string or Unicode, function found
Below is my modified app\urls.py:
from django.conf.urls import url, include
from django.contrib.auth.views import login
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
# Examples:
#url(r'^$', 'app.views.home', name='home'),
# url(r'^app/', include('app.foo.urls')),
# login
url(r'^registration/login/$', login, name=login),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^gitstack/', include('gitstack.urls')),
# url(r'^rest/', include('rest.urls')),
]
Here is my modified gitstack/urls.py
from django.conf.urls import url, include
from .views import index, users, groups, repository_permission, add_repo_user_dialog, add_repo_group_dialog, group_user, add_group_user_dialog, settings_general, settings_authentication, settings_security, log_me_out
urlpatterns = [
# standard user interface
url(r'^$', index, name='index'),
url(r'^users/', users, name='users'),
url(r'^groups/', groups, name='groups'),
url(r'^repository/(?P<repo_name>.+)/permission/$', repository_permission, name='repository_permission'),
# add users dialog
url(r'^repository/(?P<repo_name>.+)/permission/adduser/$', add_repo_user_dialog, name= 'add_repo_user_dialog'),
url(r'^repository/(?P<repo_name>.+)/permission/addgroup/$', add_repo_group_dialog, name='add_repo_group_dialog'),
url(r'^group/(?P<group_name>.+)/user/$', group_user, name='group_user'),
# add users dialog (for the group)
url(r'^group/(?P<group_name>.+)/user/add/$', add_group_user_dialog, name='add_group_user_dialog'),
# settings tab
url(r'^settings/general/', settings_general, name='settings_general'),
url(r'^settings/authentication/', settings_authentication, name='settings_authentication'),
url(r'^settings/security/', settings_security, name='settings_security'),
url(r'^logout/', log_me_out, name='log_me_out'),
]
urlpatterns should be a Python list of url() instances. So you need to remove 'gitstack.views', from urlpatterns in gitstack/urls.py
UPD
Also you have problem with login pattern. Name should be string. Change url(r'^registration/login/$', login, name=login) to url(r'^registration/login/$', login, name='login')
I have a problem with django-comments-xtd when I try to work with django 1.9. I'm following this tutorial. When I work with Django 1.8 everything is fine. But if I use Django 1.9 I get the error when I send a message.
TypeError at /comments/post/
get_comment_create_data() got an unexpected keyword argument 'site_id'
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/comments/post/
Django Version: 1.9.4
Python Version: 3.4.3
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'pagedown',
'crispy_forms',
'markdown_deux',
'django_comments',
'django_comments_xtd',
'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']
Traceback:
File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django/views/decorators/http.py" in inner
42. return func(request, *args, **kwargs)
File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django_comments/views/comments.py" in post_comment
108. comment = form.get_comment_object(site_id=get_current_site(request).id)
File "/home/olga/.virtualenvs/my_site/lib/python3.4/site-packages/django_comments/forms.py" in get_comment_object
121. new = CommentModel(**self.get_comment_create_data(site_id=site_id))
Exception Type: TypeError at /comments/post/
Exception Value: get_comment_create_data() got an unexpected keyword argument 'site_id'
I set the SITE_ID in settings.py
In theory django-comments-xtd is compatible with django 1.9
I've got the same issue when I work with my own project (dj 1.9). And even when I run the example (dj 1.9) for tutorial. Everything is fine until I send a message.
Here is forms.py of my own app.
from django import forms
from pagedown.widgets import PagedownWidget
from .models import Post
class PostForm(forms.ModelForm):
content = forms.CharField(widget=PagedownWidget(show_preview=False))
publish = forms.DateField(widget=forms.SelectDateWidget())
class Meta:
model = Post
fields = ['title', 'content', 'image']
from django.utils.translation import ugettext_lazy as _
from django_comments_xtd.forms import XtdCommentForm
class MyCommentForm(XtdCommentForm):
def __init__(self, *args, **kwargs):
if 'comment' in kwargs:
followup_suffix = ('_%d' % kwargs['comment'].pk)
else:
followup_suffix = ''
super(MyCommentForm, self).__init__(*args, **kwargs)
for field_name, field_obj in self.fields.items():
if field_name == 'followup':
field_obj.widget.attrs['id'] = 'id_followup%s' % followup_suffix
continue
field_obj.widget.attrs.update({'class': 'form-control'})
if field_name == 'comment':
field_obj.widget.attrs.pop('cols')
field_obj.widget.attrs.pop('rows')
field_obj.widget.attrs['placeholder'] = _('Your comment')
field_obj.widget.attrs['style'] = "font-size: 1.1em"
if field_name == 'url':
field_obj.help_text = _('Optional')
self.fields.move_to_end('comment', last=False)
urls.py of my app
from django.conf.urls import url
from django.contrib import admin
from .views import (
post_create,
post_detail,
post_list,
post_update,
post_delete
)
urlpatterns = [
url(r'^create/$', post_create, name='create'),
url(r'^$', post_list, name='list'),
url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', post_update, name='update'),
url(r'^(?P<slug>[\w-]+)/delete/$', post_delete),
]
urls.py
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^comments/', include('django_comments_xtd.urls')),
url(r'^', include("blog.urls", namespace ="blog")),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I guess that link can help you. I have the same error and it disappeared when I added **kwargs to custom get_comment_create_data() method, as claudep said.
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'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')