Template Does not exist - django

I am new to Django. I use pydev eclipse as an IDE. First I created a project then an application welcome on that project. I made a folder named Templates within the project and make a file "home.html" and home.html contains
<div>
This is my first site
</div>
I modify the settings.py file as
TEMPLATE_DIRS = ("Templates")
INSTALLED_APPS = (
..........#all default items
'welcome', #the added one
)
views.py includes
from django.shortcuts import render_to_response
def home(request):
return render_to_response('home.html')
urls.py contains
from django.conf.urls import patterns, include, url
from welcome.views import home
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MajorProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^home/$', home),
)
then I run it as django project and open my browser and see on localhost:8000/home
it shows error
TemplateDoesNotExist at /home/
home.html
Request Method: GET
Request URL: http://localhost:8000/home/
Django Version: 1.6
Exception Type: TemplateDoesNotExist
Exception Value:
home.html
Exception Location: C:\Python27\django\template\loader.py in find_template, line 131
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\MajorProject',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\MajorProject',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Windows\\SYSTEM32\\python27.zip']
Server time: Sun, 2 Jun 2013 14:25:52 +0545

Try to set Templates Directory on setting.py.
as
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__),'templates'),
)

If you're using Django 1.8+
You'll get this warning:
(1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_DIRS, TEMPLATE_DEBUG.
Add your template directory to the Base TEMPLATES setting under the DIRS dictionary
Like so:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
root("templates"), #### Here ####
],
'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',
],
},
},
]

in Django 1.9
in settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR+r'\templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
...
],
},
},
]

Directory with templates should be named templates, not Templates (even though on windows it may be the same). Also make sure, you have application in PYTHONPATH or the correct directory structure of your project and application like:
project/
project/
settings.py
...
welcome/
templates/
home.html
views.py
...
manage.py
Then you don't need to change TEMPLATE_DIRS because app_directories.Loader (enabled by default) will find the templates in your application.
Also of if you still want to change TEMPLATE_DIRS, use absolute paths, but preferred way is the app_directories.Loader.

check below steps to fix
step 1:
Inside templates, 'DIRS' : [ ], metion this:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
step 2:
Go in your views.py file and look for template_name (check its spelling and also check did you mentioned the right html file here or not)
step 3:
Check in your urls.py file wether you mentioned the right template name or not in the path
format: urlpatterns = [ path(" ", class name or function name, name = template name)

BASE_DIR = Path(file).resolve().parent.parent
This is default directory code by Django
And looks like this
C:\user\pc_name\django_project
But if you delete last .parent it will looks like this
C:\user\pc_name\django_project\django_project
So new BASE_DIR code which is this
BASE_DIR = Path(file).resolve().parent
Add this variable to TEMPLATE_DIR
TEMPLATE_DIR = os.path.join(BASE_DIR, 'template")
And last code define this
C:\user\pc_name\django_project\django_project\template
In the end safely uptade DIRS
'DIRS': 'TEMPLATE_DIR'
Hope you did

Related

Django base template location

I am creating a website using Django 2.0.7. I need to use a base template that is outside the purview of all applications, but can be inherited and used by templates in my other applications in the project.
I have edited my settings.py file appropriately (as per the documentation), but still when I go the root (i.e. home) page of my site, I get a blank page - can anyone explain why?
I have the following directory structure
myproj
----manage.py
----app1
----templates/
base.html
index.html
----static/
----myproj
__initi__.py
wsgi.py
settings.py
urls.py
views.py # <- I added this
The relevant parts of my settings.ini file looks like this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['{0}/templates/'.format(BASE_DIR),],
'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',
],
},
},
]
views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse()
Why can't django find my index.html ?
Use 'DIRS': [os.path.join(BASE_DIR, "templates")] in your settings, and your view should return a object which knows what template to render, like this one:
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
There's also TemplateResponse(), SimpleTemplateResponse() and other objects you can return, depending on your needs.

Django - Tutorial - Setting IndexView but Getting TemplateDoesNotExist

I have searched through all the questions here already on TemplateDoesNotExist.
I have also been troubleshooting this for about 12 hours.
There is something I am not understanding. I am new to django.
I am following the following Thinkster tutorial:
Building Web Applications with Django and AngularJS
Here is the error:
Exception Location: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loader.py in select_template, line 47
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\Workstation333\AppData\Local\Programs\Python\Python36\lib\site-packages\rest_framework\templates\index.html (Source does not exist)
This IndexView code I do not understand, and I believe is where the problem lies. The tutorial doesn't go over this code. I think this is what changes the index.html or how to find it. This is inside my views.py and is same project folder where my urls.py is located.
views.py
from django.views.decorators.csrf import ensure_csrf_cookie
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator
class IndexView(TemplateView):
template_name = 'index.html'
#method_decorator(ensure_csrf_cookie)
def dispatch(self, *args, **kwargs):
return super(IndexView, self).dispatch(*args, **kwargs)
url.py
from django.contrib import admin
from django.urls import path, re_path, include
from rest_framework_nested import routers
from authentication.views import AccountViewSet
from HawkProject.views import IndexView
router = routers.SimpleRouter()
router.register(r'accounts', AccountViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/v1/', include(router.urls)),
re_path(r'^.*$', IndexView.as_view(), name='index')
]
partial settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
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',
],
},
},
]
Please help, and Thank you.
Edit:
I added the following to the code, and I got it to not break right away,
but I don't think it is a solution, but a hack that will break, or is not maintainable. I added the index for the admin index inside Dirs like so:
'DIRS':
['C:/Users/Workstation333/AppData/Local/Programs/Python/Python36/Lib/site-
packages/django/contrib/admin/templates/admin'],
I couldn't find the other index files in the directories where it thinks they should have been. *notice the double admin in the directory above, not sure why that is. It also makes the "home" page take me directly to the admin page.
I haven't read through the tutorial you are doing but try doing this:
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',
],
},
},
]
As you can see, I think you are getting this error because your template directory 'DIRS' is blank and as such Django does not know where to search for 'index.html'. The 'templates' name can be changed to any name you want but just name it according to the folder which you keep your templates in within each of your apps.
Django Templates

Page not found: http://127.0.0.1:8000/sitemap.xml/

Here are the codes to create the sitemap for one of my app 'blog' in my site: (using Django 2.0)
settings.py
INSTALLED_APPS += [
'django.contrib.sites',
'django.contrib.sitemaps',
]
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',
],
},
},
]
urls.py
from django.urls import include, path
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSiteMap
sitemaps = {'posts': PostSiteMap}
urlpatterns += [
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap')
]
sitempas.py (under 'blog' app directory)
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSiteMap(Sitemap):
changefreq = 'weekly'
priority = 0.5
def items(self):
return Post.published.all()
def lastmod(self, obj):
return obj.publish
The sitemap.xml doesn't appear: http://127.0.0.1:8000/sitemap.xml/
There is the url (the eighth) matching my inputted one. Why it says 'not match'?
Your code is good, your environment is what is wrong (maybe you are using the default Django site, that is www.example.com). Change it to a local environment (the typical 127.0.0.1:8000).
To do this in Django you need to do the following:
Check if you are running the local server in your command prompt, if is not, type python manage.py runserver.
go to http://127.0.0.1:8000/admin/sites/site/
Change the default site (typically the default in Django is example.com) to 127.0.0.1:8000. This needs to be done in the domain and display name (while you aren't in a production environment).
Press F5 in your local web page in your browser.
go to your sitemap page (http://127.0.0.1:8000/sitemap.xml)
And voilĂ ! there is your sitemap.
Write full /sitemap.xml like this and try
Enter this url and load page
http://127.0.0.1:8000/sitemap.xml/
The error is
Site matching query does not exist
which means that you have to setup and configure Sites framework.
To enable the sites framework, follow these steps:
Add 'django.contrib.sites' to your INSTALLED_APPS setting.
Define a SITE_ID setting:
SITE_ID = 1
Run migrate.
For more information check documentation.

Jinja2 throwing templatedoesnotexist error in Django project

I'm trying to use jinja2 in my Django project (ver 1.10). After setting it up, once I try to run the project, I get TemplateDoesNotExist at /base/index.html and
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine jinja2:
This engine did not provide a list of tried templates.
In templates folder, I have a base directory where index.html is placed. Moreover, if I use Django's template engine, this same folder structure works perfectly. How can I fix this issue?
My config is as follows:
In settings.py (note that I've deliberately excluded the Django template fallback):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {'environment': 'uberfordoc.jinja2.environment',
},
},
]
I also have a file called jinja2.py kept in the project folder:
from __future__ import absolute_import
from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse
from jinja2 import Environment
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env
This was my BASE_DIR and MAIN_DIR in settings.py
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MAIN_DIR = os.path.dirname(os.path.dirname(__file__))
and my jinja2 templates were at the path
/Users/username/Desktop/uberfordoc/templates/jinja2
changed
'DIRS': [os.path.join(BASE_DIR, 'templates')],
to
'DIRS': [os.path.join(MAIN_DIR, 'templates/jinja2')],
and it worked. Got the hint thanks to #Timbadu by printing
print os.path.join(BASE_DIR, 'templates')

TemplateDoesNotExist at /rango/

I have tried my best to source and to fix this problem, but I can't seem to find the answer.
Currently going through the tangowithdjango tutorial, I'm currently on 5. Templates and Static Media.
http://www.tangowithdjango.com/book17/chapters/templates_static.html
Trying to get my site to show its first template, but just before I reach 5.2 I tried loading my site and got this error message:
TemplateDoesNotExist at /rango/
rango/index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/rango/
Django Version: 1.8
Exception Type: TemplateDoesNotExist
Exception Value:rango/index.html
Exception Location: /Library/Frameworks/Python.framework/Versions/2.7/lib
/python2.7/site-packages/django/template/loader.py in get_template, line 46
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7
/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.9
Here is my settings.py file:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
# Template from tangowithdjango 5.1: Templates and Static Media
#
TEMPLATE_DIRS = (
# 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.
TEMPLATE_PATH,
)
Here is my views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
# Construct a dictionary to pass to the template engine as its context.
# Note the key boldmessage is the same as {{ boldmessage }} in the template!
context_dict = {'boldmessage': "I am bold font from the context"}
# Return a rendered response to send to the client.
# We make use of the shortcut function to make our lives easier.
# Note that the first parameter is the template we wish to use.
return render(request, 'rango/index.html', context_dict)
Sorry about the comments, after a few tries I copied the site's code, but still to no success.
My file structure is as follows:
workspace
tango_with_django_project
manage.py
tango_with_django_project
settings.py
templates
rango
index.html
To add, here is what is shown at 127.0.0.1:8000/rango :
Template-loader postmortem
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/site-packages/django/contrib/admin/templates/rango/index.html (File does not exist)
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
/site-packages/django/contrib/auth/templates/rango/index.html (File does not exist)
TEMPLATE_DIRS is deprecated in django 1.8. You should use the TEMPLATES setting instead. Chances are that you already have the TEMPLATES variable in the settings.py so alter the DIRS key like this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_PATH], # <-- HERE --
'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',
],
},
},
]
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
Add this below BASE_DIR:
PROJECT_PATH = os.path.join(BASE_DIR, os.pardir)
Next following should look like this:
STATIC_PATH = os.path.join(PROJECT_PATH, 'tango_with_django_project/static')
STATIC_URL = '/static/'
STATICFILES_DIRS =(
STATIC_PATH,
)
TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'tango_with_django_project/templates')
TEMPLATE_DIRS = (
TEMPLATE_PATH,
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'tango_with_django_project/media')
Your directory structure is wrong. check out what this code is doing...
directory = os.path.dirname(os.path.abspath(__file__))
according to your directory structure this code returns...
/root_path/tango_with_django_project/tango_with_django_project
therefore according to your structure, templates folder is not inside the folder tango_with_django_project which is where it thinks it should be.
you could just specify a direct path to your templates if you want.
TEMPLATE_PATH = '/root_project/tango_with_django_project/templates/'
On a side note, Tango with Django is the worst name for a tutorial series, possibly ever.