Django template Module Import Error - python

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)

Related

TemplateDoesNotExist in Django views

I'm new to Django, currently following the tutorial on the Django site for polls:
https://docs.djangoproject.com/en/4.1/intro/tutorial03/
I'm not able to render my template when using polls/index.html. I have followed along verbatim, yet when i try to render the request in the views.py file, I am getting a TemplateDoesNotExist error, which states that the source is not found. What I don't understand is my index.html is located in the correct location (IE, mysite > polls > template > polls > index.html) and my main settings are exactly how the tutorial states. I've tried the frequently suggested (if dated) response of adding os.path.join(SETTINGS_PATH, 'templates'), however the issue persists.
I'm currently running Python 3.10 with Django 4.1, yet this shouldn't be the problem. I've confirmed that my index.html file is in the correct location, being stored in templates > polls > index.html.
settings.py
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',
],
},
},
]
views.py
import requests
from .models import Question
from django.http import HttpResponse
from django.template.loader import get_template
# Create your views here.
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
Error
polls/index.html
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/
Django Version: 4.1
Exception Type: TemplateDoesNotExist
Exception Value:
polls/index.html
Exception Location: C:\Users\patbc\myproject\lib\site-packages\django\template\loader.py, line 19, in get_template
Raised during: polls.views.index
Python Executable: C:\Users\patbc\myproject\Scripts\python.exe
Python Version: 3.10.4
Python Path:
['C:\\Users\\patbc\\myproject\\mytestsite',
'C:\\Python310\\python310.zip',
'C:\\Python310\\DLLs',
'C:\\Python310\\lib',
'C:\\Python310',
'C:\\Users\\patbc\\myproject',
'C:\\Users\\patbc\\myproject\\lib\\site-packages']
Server time: Tue, 23 Aug 2022 20:33:42 +0000
Here is my directory structure (note that index.html resides in the proper subdirectory, 'polls'):
link
You have named the folder wrong. It should be plural - templates, not template.

Django - why are my paths going through anaconda?

When i put a return render code in my views.py I get an error when i go to http://localhost:8000/
Also why are my paths going through anaconda?
I don't get this error when I do this
from django.http import HttpResponse
def home(request):
return HttpResponse("YorleƬ's")
I've included my Template settings
from django.shortcuts import render
# Create your views here.
def home(request):
return render (request, 'homepage/home.html')
TemplateDoesNotExist at /
homepage/home.html
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 3.1.2
Exception Type: TemplateDoesNotExist
Exception Value: homepage/home.html
Exception Location: /Users/yorleydis/opt/anaconda3/lib/python3.8/site-packages/django/template/loader.py, line 19, in get_template
Python Executable: /Users/yorleydis/opt/anaconda3/bin/python
Python Version: 3.8.3
Python Path:
['/Users/yorleydis/yorleico',
'/Users/yorleydis/opt/anaconda3/lib/python38.zip',
'/Users/yorleydis/opt/anaconda3/lib/python3.8',
'/Users/yorleydis/opt/anaconda3/lib/python3.8/lib-dynload',
'/Users/yorleydis/opt/anaconda3/lib/python3.8/site-packages',
'/Users/yorleydis/opt/anaconda3/lib/python3.8/site-packages/aeosa']
Server time: Sun, 29 Nov 2020 12:53:02 -0500
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',
],
},
},
]

Django Developments Template_DIRS setting failed

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'),],

Can't load a template in Django - 'TemplateDoesNotExist at /home/' error

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.

How to integrate django-rest-swagger 2.0 with existing DRF application(Beginner)

I am trying to integrate swagger 2.0 with existing DRF application but it gives following error in browser after runningpython manage.py runserver:
TemplateDoesNotExist at /swagger rest_framework_swagger/index.html
Request Method: GET Request URL: http://127.0.0.1:8000/swagger
Django Version: 1.10 Exception Type: TemplateDoesNotExist Exception
Value: rest_framework_swagger/index.html Exception
Location: C:\Users\MHAZIQ~1\Desktop\Tkxel\mmg-git\venv\lib\site-packages\django\template\loader.py
in get_template, line 25
I have added following lines in
views.py:
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='Pastebin API')
And I have added following lines in
urls.py:
url(r'^swagger', views.schema_view),
I ve tried applying following solution:
TemplateDoesNotExist at /docs/ rest_framework_swagger/index.html
but it didnot solve my problem, Can anyone please help me in this regard?
Add 'rest_framework_swagger' to INSTALLED_APPS in Django settings.
settings.py
INSTALLED_APPS = [
...
'rest_framework_swagger',
]
https://django-rest-swagger.readthedocs.io/en/latest/
After several hours of research I have found the problem with my code, as I was adding swagger into an existing project, it didnt have following parameters in settings.py:
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',
],
},
},]
Now swagger works absolutely fine!

Categories

Resources