Django templateview not recognizing my template_name - python

Currently I have in settings set my main directory to the templates folder so that I have a project level templates. Within that folder I have a home.html file.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
This is my views.py file:
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name: "home.html"
Whenever I runserver I receive this error: ImproperlyConfigured at /
TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I'm following a book to the T (Django for Beginners) and I'm unsure why this error could be happening. Has the syntax for template_name changed? I've checked all the documentations and my name seems to be okay. I've also tried to input the pathname to the file instead.

You are making an annotation: you should use an equals sign = instead of a colon ::
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'home.html'
Normally templates are also "namespaced" by putting these into a directory with the name of the app, so:
from django.views.generic import TemplateView
class HomePageView(TemplateView):
template_name = 'app_name/home.html'
and thus put the template in the directory of the app_name/templates/app_name/home.html. This prevents that you later would collide with a template with the same name in a different app.

You have used the view incorrectly. Replace the : with = and it should be fine.

Related

I am getting Template Does Not Exist at / when I'm running my server in Django

When I run server I get Template Does Not Exist at / for my index.html page. Same problem occurs for other templates as well.
I've tried the solutions for previously asked similar questions like checking the template directory and installed apps in settings.py file but nothing seems working.
Also, when I create a new project folder at some other location and copy all the code there, it usually works.
This is my folder tree:
I'm currently learning Django and new at stack overflow. Any help would be appreciated?
Here is my urls.py code for project folder:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from basic_app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
path('admin/', admin.site.urls),
url(r'basic_app/',include('basic_app.urls')),
]
Here is my urls.py file under basic_app:
from django.conf.urls import url
from basic_app import views
app_name= 'basic_app'
urlpatterns=[
url(r'^register/$',views.register,name='register')
]
Here is my views.py file code:
from django.shortcuts import render
from basic_app.forms import UserForm, UserProfileInfoForm
def index(request):
return render(request,'basic_app/index.html')
def register(request):
registered= False
if request.method=='POST':
user_form= UserForm(data= request.POST)
profile_form= UserProfileInfoForm(data= request.POST)
if user_form.is_valid() and profile_form.is_valid():
user= user_form.save()
user.set_password(user.password)
user.save()
profile= profile_form.save(commit=False)
profile.user=user
if 'profile_pic' in request.FILES:
profile.profile_pic= request.FILES['profile_pics']
profile.save()
registered= True
else:
print(user_form.errors ,profile_form.errors)
else:
user_form= UserForm()
profile_form= UserProfileInfoForm()
return render(request,'basic_app/registration.html',{'user_form':user_form,'profile_form':profile_form,
'registered':registered})
Here is my settings.py file code for templates:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
MEDIA_DIR=os.path.join(BASE_DIR,'media')
This is my Installed app list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'basic_app',
]
Also this:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_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',
],
},
},
]
I think in admin just do this
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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 your view should be something like this
return render(request,'basic_app/registration.html',{'user_form':user_form,'profile_form':profile_form,
'registered':registered})
hope this helps
In your settings.py check the directory pointed by TEMPLATE_DIR so that you can configure where exactly it is ponting to.
print(TEMPLATE_DIR)
Then in views.py:
def index(request):
return render(request,'folder/my_html_file.html')
So django renders the template from.
TEMPLATE_DIR + "folder/my_html_file.html"
If you are using the default configuration settings, the templates are supposed to be in learning_users/basic_app/templates/basic_app/ and accessed like the following:
return render(request, `basic_app/index.html`, {})
where index.html is your template name.
The directory structure here may seem a little redundant at first but you can also change it using the settings.py configuration file.
In your directory, the templates folder is placed directly inside the project folder (i.e. learning_users). Unless you have modified the configuration files to change the templates' path, this would result in an Error.
but perhaps you can do this sure it works in your settings.py file add this line to the installed apps
'basic_app.apps.Basic_appConfig'

Why console is showing templates not defined error in django

I am new to django , I am facing one while django running server , I have copy and paste my code please tell me what is wrong with my code
'DIRS': [templates],
NameError: name 'templates' is not defined
in settings.py file , I have put templates in [] brackets
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [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',
],
},
},
]
this is my views.py
from django.http import HttpResponse
from django.shortcuts import render
def index(response):
return render(request,'index.html')
this is urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('about', views.about, name='about'),
]
templates should be string. so ['templates'] instead of [templates]
You need to change DIRS here
'DIRS': [os.path.join(BASE_DIR, 'templates')],
Here, Django expects it has a template path but you provide templates variable which does not have any path.
While others have already given right answers on how to fix it, but I would like to point out a minor thing that you are getting the NameError because you haven't defined the name templates.
The NameError is raised when the variable you are using is not defined anywhere in the program (if you defined it outside the current scope you will be getting UnboundLocalError).
If you define the name templates as a string for the absolute path to your template folder, this will work. Still, never use absolute path in your Django application cause it will become a headache while deployment.
You have to change your line to this
'DIRS': [os.path.join(BASE_DIR, 'templates')],
In the begging of the settings files you can see the BASE_DIR
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Changing DIRS to
'DIRS': [os.path.join(BASE_DIR, 'templates')],
Will help the app to find the templates folder.
Just a personal advice in each app store the templates/appname folder for the specific app. It will help you to have a more robust Django app.
for example you have the polls app, inside the polls app it will be like this
pollsApp/templates/pollsApp/index.html etc.
Also here is the official guide, it might help you

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

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.

TemplateDoesNotExist at /board/boards

I got this error during the python django project
I do not understand why the template does not connect.
Please let me know which part of the error it is and let me know how to fix it.
How can I to do?
Attach an error picture.
enter image description here
settings.py
INSTALLED_APPS = [
--- skip ---
board.apps.BoardConfig',
]
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',
],
},
},
]
These are my project sub-lists
/mysite
/board
/migrations
/templates
/board
board_list.html
board_detail.html
search.html
__init__.py
admin.py
apps.py
forms.py
models.py
tests.py
urls.py
views.py
/mysite
__init__.py
settings.py
urls.py
views.py
wsgi.py
/static
css
js
image
/templates
base.html
main.html
db.sqlite3
manage.py
/mysite/mysite/urls.py
from django.contrib import admin
from django.conf.urls import url, include
from .views import MainHome
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', MainHome.as_view(), name='main'),
url(r'^board/', include('board.urls', namespace='board'),
]
/mysite/board/urls.py
from django.conf.urls import url
from .views import *
from mysite.views import MainHome
app_name = 'board_app'
urlpatterns = [
url(r'^$', MainHome.as_view(), name='main'),
url(r'^search/$', SearchFormView.as_view(), name='search'),
url(r'^boards/$', BoardList.as_view(), name='board_list'),
url(r'^boards/(?P<slug>[-\w]+)/$', BoardDetail.as_view(), name='board_detail'),
]
/mysite/borad/views
from .models import Board
from django.views.generic import ListView
--- skip ---
class BoardList(ListView):
model = Board
template_name = 'board_list.html'
content_object_name = 'boards'
paginate_by = 10
--- skip ---
In /mysite/borad/views, you have:
template_name = 'board_list.html'
Replace it with:
template_name = 'board/board_list.html'
Because board_list.html is inside templates/board.
Edit
In settings.py, you have:
'DIRS': [os.path.join(BASE_DIR, 'templates')],
which means that Django will look for templates in your mysite/templates folder. Remove it like this:
'DIRS': []
so Django will look by default inside templates/ directory for every installed app.
Your template is inside board directory. And your model template name is not referencing to that path.
In your class BoardList add template_name = 'board/board_list.html'
I'd try a systematic approach:
in settings.py, define TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
Given your directory structure, your app name is board not board_app. So, set INSTALLED_APPS = [..., 'board']. Also, I don't understand in your code why you refered to board.apps.BoardConfig instead of board, maybe am I missing something
TEMPLATES = [{ .... 'DIRS': [TEMPLATE_DIR], ... }] will make things more visible
in urls.py of board app, set app_name=board
in views.py, if you use Django naming conventions for file / directories, you don't need to specify the template name for class based views. Remove template_name = 'board_list.html provided your template is in board/templates/board/board_list.html
Also, reboot the server after performing those changes.
Does this help?

Categories

Resources