django.template.loader can't find template - python

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!

Related

TemplateDoesNotExist Error in django on a simple hello world project

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"

Template Does not exist error while deploying on pythonanywhere

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.

TemplateDoesNotExist at /polls/ index.html

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.

using Tinymce for django error.

I am trying to use TinyMCE Editor in django for textarea. I followed the instructions given on django-tinymce.readthedocs.org/en/latest/usage.html#python-code which give me a error
Environment:
Request Method: GET
Request URL: http://localhost:8000/home/
Django Version: 1.6.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce')
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')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/hussain/django/ali/ali/views.py" in HomePage
6. print " form :: ",form
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/utils/encoding.py" in <lambda>
60. klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in __str__
103. return self.as_table()
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in as_table
223. errors_on_separate_row = False)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in _html_output
186. 'field': six.text_type(bf),
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in __str__
425. return self.as_widget()
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/forms.py" in as_widget
475. return widget.render(name, self.value(), attrs=attrs)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/widgets.py" in render
572. options = self.render_options(choices, value)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/widgets.py" in render_options
528. for option_value, option_label in chain(self.choices, choices):
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/forms/models.py" in __iter__
1044. for obj in self.queryset.all():
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/query.py" in __iter__
96. self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/query.py" in _fetch_all
854. self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/query.py" in iterator
220. for row in compiler.results_iter():
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/sql/compiler.py" in results_iter
710. for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
781. cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/util.py" in execute
69. return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/util.py" in execute
53. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/utils.py" in __exit__
99. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/util.py" in execute
53. return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/Django-1.6.1-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
450. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /home/
Exception Value: no such table: django_site
I feel to stupid to not get this. :'(.
these are my files.
settings.py
"""
Django settings for ali 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__))
# Django settings for corating project.
PROJECT_DIR = os.path.dirname(__file__)
print 'BASE_DIR ',BASE_DIR
print 'PROJECT_DIR ',PROJECT_DIR
# 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 = '-=153zwy^8$sz%gsw#kb377pp#r3wmcer(4tc$j-h4(^3s+zw+'
# 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',
'tinymce',
)
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 = 'ali.urls'
WSGI_APPLICATION = 'ali.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static_root')
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'static'),
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
TINYMCE_JS_URL = os.path.join(STATIC_URL, "js/tiny_mce/tiny_mce.js")
TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "js/tiny_mce")
print "TINYMCE_JS_ROOT ",TINYMCE_JS_ROOT
print "TINYMCE_JS_URL ",TINYMCE_JS_URL
TEMPLATE_DIRS = (
'/home/hussain/django/ali/ali/templates/',
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
forms.py
from django import forms
from django.contrib.flatpages.models import FlatPage
from tinymce.widgets import TinyMCE
class FlatPageForm(forms.ModelForm):
content = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
class Meta:
model = FlatPage
views.py
from django.shortcuts import render_to_response
from page.forms import FlatPageForm
def HomePage(request):
form = FlatPageForm()
print " form :: ",form
return render_to_response('HomePage.html',{'form':form})
urls.py
from django.conf.urls import patterns, include, url
from ali.views import HomePage
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'ali.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
#url(r'^admin/', include(admin.site.urls)),
url(r'^home/', 'ali.views.HomePage' ),
url(r'^tinymce/', include('tinymce.urls') ),
)
You don't seem to have installed flatpages app. Also flatpages app depends in sites framework Follow the steps in the documentation to get it right:
--- excerpts --
To install the flatpages app, follow these steps:
Install the sites framework by adding 'django.contrib.sites' to your INSTALLED_APPS setting, if it’s not already in there.
Also make sure you’ve correctly set SITE_ID to the ID of the site the settings file represents. This will usually be 1 (i.e. SITE_ID = 1, but if you’re using the sites framework to manage multiple sites, it could be the ID of a different site.

template not found for Django homepage

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

Categories

Resources