I am trying to render a response back to an Ajaz request. The view is reached in the python code, but if I try and render the response to string using render_to_string then I get an error stating:
django.template.exceptions.TemplateDoesNotExist:
If I run the render method with the same parameters then I don't get an error. The code for each looks like:
html = render_to_string(request, 'planner/viewconnections.html', { 'routes' : routelist })
render(request, 'planner/viewconnections.html', { 'routes' : routelist })
Obviously the first one is what I want to run so I can obtain the raw html back to the AJAX success function.
My templates configuration in settings.py looks like:
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',
],
},
},
]
I have tried adding the template directory as below, but I still get the same error.
ROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname((__file__)),".."))
# Other settings...
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, "planner/templates"),
)
Can someone help? My search on this problem let me to add the TEMPLATE_DIRS in settings, but that didn't work. I don't understand why one render method can pick up the template, but the other doesn't.
in django render_to_string request paramter is not required
syntax
render_to_string(template_name, context=None, request=None, using=None)
html = render_to_string('planner/viewconnections.html', { 'routes' : routelist })
refer this https://docs.djangoproject.com/en/2.1/topics/templates/#django.template.loader.render_to_string
Related
Using Django version 1.9.5 and Python 3.
Upon navigation to the url, I am getting the following error:
ImportError at /music/
No module named 'django.templates'
Request Method: GET
Request URL: http://localhost:8000/music/
Django Version: 1.9.5
Exception Type: ImportError
Exception Value:
No module named 'django.templates'
Exception Location: D:\Program Files (x86)\Python\lib\importlib\__init__.py in import_module, line 126
Python Executable: D:\Program Files (x86)\Python\python.exe
Python Version: 3.5.0
Python Path:
['C:\\Users\\ang\\Desktop\\website',
'D:\\Program Files (x86)\\Python\\lib\\site-packages\\django-1.9.5-py3.5.egg',
'D:\\Program Files (x86)\\Python\\python35.zip',
'D:\\Program Files (x86)\\Python\\DLLs',
'D:\\Program Files (x86)\\Python\\lib',
'D:\\Program Files (x86)\\Python',
'D:\\Program Files (x86)\\Python\\lib\\site-packages']
The error seems to be coming from the import line. Checked syntax and tried to explicitly provided the path under TEMPLATES at DIRS but same result. Anyone encountered a similar issue? Found some similar issues raised but in different languages.
Folder Structure for template: name_of_app/templates/inner_folder/html_file
music/templates/music/index.html
views.py
from django.http import HttpResponse
from django.template import loader # error gone if i remove this line
from .models import Album
def index(request):
all_albums = Album.objects.all()
template = loader.get_template('music/index.html')
context = {
'all_albums': all_albums
}
return HttpResponse('test test')
settings.py
TEMPLATES = [
{
'BACKEND': 'django.templates.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.templates.context_processors.debug',
'django.templates.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
This looks like the programmer's greatest nemesis: a typo. You can see midway in the 2nd code snippet a reference to django.templates..., but your 2nd line is importing from django.template.
Edit: From my testing, an incorrect import will fail in the shell, and an incorrect reference in context_processors will fail in the browser.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Try to use this method to render your template using module django.shortcurt.render():
from django.shortcuts import render
from .models import Album
def index(request):
all_albums = Album.objects.all()
context = {
'all_albums': all_albums
}
return render(request, 'music/index.html',context=context)
I was recently trying to learn Django for one of my private project.
When came to the Chapter on Template,the Django Book recommended setting template path in settings.py using the the following snippet
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__),'templates').replace('\\','/'),)
However ,when I opened the file setting.py I found nothing like "TEMPLATE_DIR" but a list:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),],
'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 the value related to the key "DIR",was a empty list. So I try to filled it with the content shown above.
And then, code something in the views.py(all the import was done )
def current_datetime(request):
now = datetime.datetime.now()
t = get_template("current_datetime.html")
html = t.render(Context({"current_date" : now}))
return HttpResponse(html)
And then mkdir templates in the same folder with setting.py , saved current_datetime.html in folder templates
Finally,run the project.and got the message in my terminal:
WARNINGS:
?: (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.
System check identified 1 issue (0 silenced).
June 15, 2017 - 15:32:49
Django version 1.11.2, using settings 'mysite.settings'
Starting development server at 127.0.0.1:8000/
Quit the server with CONTROL-C.
When opened the address (127.0.0.1:8000/time/) in my Safari,here came the
error message:
enter image description here
Anyone help,please ??
There is a warning on TEMPLATE_DIRS, for that just be sure you don't have TEMPLATE_DIRS variable in your settings.py and restart development server.
Then for the error, you are actually using a Context object instead of a dict, you should render the template using a useful shortcut https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#example
from django.shortcuts import render
def current_datetime(request):
now = datetime.datetime.now()
return render(request, "current_datetime.html", {
'current_date' : now,
})
I think you have BASE_DIR in settings.py for define location so use like below
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',
],
},
},
DIRS should be like below
'DIRS': [os.path.join(BASE_DIR, 'templates'),],
I'm learning Django from 'Mastering Django: Core' book and now I'm
stucked in this third chapter of the book which describes about the Django template.
The problem I'm facing is I can't load a template from a specific directory because it gives me this "TemplateDoesNotExist at /home/" error.
Here is my project directory :
mywebsite/
mywebapp/
...
...
views.py
...
temp/
template.html
Here is TEMPLATES list from settings.py :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/home/temp'],
'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 finally here's my view :
from django.template.loader import get_template
def home(request):
t = get_template("template.html")
c = Context({'heading':'Welcome to MyWebsite.',
'name':'Arya Stark','age':19})
return HttpResponse(t.render(c))
Note: The template I'm using in this view is in the temp directory.
So, can you please explain me why would that error happen?
You've set DIRS to "/home/temp", but as you've clearly shown in your directory structure, your templates are in "mywebsite/temp". You'll probably need to use the full path there, or at least os.path.join(BASE_DIR, 'temp').
First of all, check if in your settings.py BASE_DIR is declared, if it is,
then check,
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Also, in your DIRS in TEMPLATES,
'DIRS' : [BASE_DIR + '/temp/',]
This should do the trick,
Also, django as default checks for the sub-directory templates in your app-directory and project-directory as well, when you APP_DIRS = True.
I am using windows, new to Django, trying to learn it.
Right now I am just trying to set up a template, views, url - and load the template in my browser. Should be simple.
I have a project folder. An app folder. A templates folder. My templates folder contains page.html which is an html file that just says "hi".
my urls is properly configured to point to my views
I have 2 views.
def frontpage(request):
fp = open('C:/EclipseWorkspace64/Project/templates/page.html')
page = Template(fp.read())
return HttpResponse(page)
def otherpage(request):
page = get_template('page.html')
return HttpResponse(page)
The first view loads my template fine when I go to the URL.
The second view does not. It gives me: [Errno 22] Invalid argument: 'C:\EclipseWorkspace64\Project\:\page.html'
This is templates in my settings:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': 'C:/EclipseWorkspace64/Project/templates/',
'APP_DIRS': False,
'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',
],
},
},
]
I don't understand why I get this error. What am I doing wrong? Why does the first view load but the second one doesn't? I have followed instructions in the django book on how to set up my settings file to a tee.
I want to divide my app to front-end and back-end in Django project. I have books app inside my project directory, so i placed JS files and index.html to myproject/books/front-end/ dir. Now i just need to render index.html in view, but for that it has to be in myproject/books/templates/. So i tried to use render_to_response('../front-end/index.html') dance, but it just renders 'no file' error.
P.S. Basic idea is to handle all template work by Handlebars and use RESTful API to communicate with server database with Tastypie. Maybe it is bad idea or i'm doing something wrong.
Consider adding the /front-end/ folder in your TEMPLATES['DIRS'][] list in your settings.py. Something like
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'books/front-end/'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
#the usual stuff
],
},
},
]
In my project with Django 1.8 I have something similar.
In views.py:
def desktop_view(request):
return render(request, 'index.html', {})