Django template does not exist # - python

I am using python 3.7.2 and Django 2.1 and every time I try to load the home url I get the following error.
TemplateDoesNotExist at /
ghostwriters/post_list.html
Request Method: GET Request URL: http://localhost:8080/ Django
Version: 2.1 Exception Type: TemplateDoesNotExist Exception Value:
ghostwriters/post_list.html
Exception Location:
C:\Users\User.virtualenvs\ghostwriter-HT06mH6q\lib\site-packages\django\template\loader.py
in select_template, line 47 Python Executable:
C:\Users\User.virtualenvs\ghostwriter-HT06mH6q\Scripts\python.exe
Doesn't make any sense because there really is no post_list.html and its not in my app level urls.py or my views.py so why is this happening?
urls.py:
from django.urls import path from .views import PostListView
urlpatterns = [
path('', PostListView.as_view(), name='home'), ]
views.py:
from django.shortcuts import render from django.views.generic import
ListView
from .models import Post
class PostListView(ListView):
model = Post
template = 'home.html'
settings.py:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,

If you are using any CBV(Class Based Views), by default django will look for template with some specific pattern. In your case, since you are using List View, it will look for YOURMODELNAME_list.html (YOURMODELNAME in lowercase), If you are extending Detail View, it will look for YOURMODELNAME_detail.html .if you want to override this behavior, within your CBV try this,
class YourCBV(ListView):
template_name = 'your_new_template.html'
For your reference,
Django official documentation

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.

Why is the Django template file not updating value from the context?

(I am a beginner in Django)
I am following along a tutorial in Django where we can dynamically pass some variable to a template file from associated function in views.py
When I am running the code for the first time, it works fine, but when I change the values within the context, the template does not update with the new values even when I refresh it
Here is my views.py code -
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# return HttpResponse('<h1>Hey, welcome</h1>')
# we can dynamically send data to our index.html file as follows -
context={
'u_name': 'Ankit',
'u_age': 25,
'u_nationality': 'Indian',
}
return render(request,'index.html',context)
Here is my template index.html -
<h1>
How are you doing today {{u_name}} <br>You are {{u_age}} years old<br>Your nationality is {{u_nationality}}
</h1>
settings.py has been correctly set as well -
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR,'templates'],
Editing post to add urls.py as well (this is within the app)
from . import views
from django.urls import include,path
urlpatterns = [
path('',views.index,name='index')
]
And the urls.py in the main project -
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls'))
]
Here is my output -
does not take the values from the context
Would be glad if someone could point out what error I am making. Thanks in advance

How to resolve 'TemplateDoesNotExist' error when Django appears to be searching the correct path

I'm setting up the structure for a new project in Django. I've created the app 'accounts', within which I've added a templates folder containing an html template. However, when I go into the development server and click on a link to this page from my index page (which loads no problem), it returns a TemplateDoesNotExist error message.
I've examined the error message and the Template-loader postmortem details the correct pathway for my html template (I've checked this and made sure countless times), suggesting that Django is looking in the right place for it. However, it also says 'source does not exist'. Does anybody have any troubleshooting tips, considering Django appears to be searching the correct pathway?
# From settings.py ('accounts' is also included with INSTALLED_APPS):
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# ...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# From urls.py:
from django.conf.urls import url, include
from accounts.views import index
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', index, name="index"),
url(r'^accounts/', include('accounts.urls')),
]
# From urls.py (accounts):
from .views import signup
urlpatterns = [
url(r'^signup/$', signup, name="signup"),
]
# From views.py (accounts):
def signup(request):
return render(request, 'signup')
I guess do you have a newer version of django on your server machine.
DIRS is now (2.2) into TEMPLATES setting var. On django old version (ex: 1.8) was in DIRS setting var.
Then, check versions and move to newest one and use:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
on settings.

DJango Template Not Found Issue

Still learning Django and for some reason I have difficulty grasping some concepts especially the url / template / view mappings. Attempting to reirect a FormView to a "Complete" page I have the following:
urls.py
from django.urls import path
from .views import *
urlpatterns = [
path('', IndexView.as_view(), name='index'),
path('forgotid/', ForgotId.as_view(),name="forgotid"),
path('forgotid/complete/',ForgotIdComplete.as_view(),name="forgotid_complete"),
path('forgotpwd/', ForgotPwd.as_view(),name="forgotpwd")
]
views.py
from django.shortcuts import render
from django.views.generic import FormView, TemplateView
from .forms import LoginForm, ForgotIDForm
class IndexView(FormView):
template_name = "login/index.html"
form_class = LoginForm
class ForgotId(FormView):
template_name = "login/forgotid.html"
form_class = ForgotIDForm
success_url = 'complete/'
class ForgotIdComplete(TemplateView):
template_name = "login/forgotid/complete/forgotid_complete.html"
def get(self, request):
return render(request, self.template_name, None)
class ForgotPwd(TemplateView):
template_name = "login/forgotpwd.html"
submitting the ForgotID form should redirect me to the success_url but I get an error stating that the template could not be found. Can someone please explain what and why I am doing this incorrectly.
The error I am receiving is:
TemplateDoesNotExist at /login/forgotid/complete/
My folder structure:
EDIT
I found the issue. The template name in the ForgotIdComplete class should read: login/forgotid_complete and notlogin/forgotid/complete/forgotid_complete.html
change your success_url to this.
from django.core.urlresolvers import reverse_lazy
class ForgotId(FormView):
template_name = "login/forgotid.html"
form_class = ForgotIDForm
success_url = reverse_lazy('forgotid_complete')
This error means that, django wanted to render the template from the path you provided but couldn't find it on the disk.
Go to settings.py and make sure that templates is configured to your actual templates directory.
PROJECT_DIR = os.path.realpath('.')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [(os.path.join(PROJECT_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',
],
},
},
]
I found the issue. The template name in the ForgotIdComplete class should read:
login/forgotid_complete
and not
login/forgotid/complete/forgotid_complete.html

How to point django to put a template in the front page

I am trying to learn python in the django framework, I took a course, but it was based on an earlier version of django while I am using Django 2.1.3 and python 3.7.0, so I've got errors.My question is how can I point urls.py to take an html template and put it in the main page in this version of Django?
Thank you!!
You should point urls.py to views.py for your home page.
So your urlpatterns would look like, your main app:
urlpatterns = [
path(r'', include('page.urls'))
]
urls.py in page app:
urlpatterns = [
url('^$', views.page, name = 'index')]
And views.py like:
def page(request):
return render(request,"page.html")
There is tons of tutorials online. Have a look on Django documentation or YouTube . I also have blog with some info (I started learning recently too) https://adamw.eu
I assume Front page stands for Home page and that your site is called website. Then in urls.py of website/website (the directory that also contains the settings.py file), create a HomePage view
from django.views.generic import TemplateView
class HomePage(TemplateView):
template_name = 'index.html'
Then in urls.pyin the same folder, do something like:
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name="home"),
]
You then need a templates folder at the root of your website, that is in website/templates and create website/templates/index.html which will be your homepage template.
In the website/website/settings.py file, make sure to set TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') and modify the TEMPLATES variable:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
... # rest of the code here
Reboot server, this should work fine.

Categories

Resources