Home > database >  Django templates rendering issue
Django templates rendering issue

Time:01-29

I'm new to Django, trying my hand at creating a web app based on the self learn tutorial. i have created a app with name "travello" and project name is "travellproject", in the views i'am trying to render a html page.

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def homepage(request):
    return render(request,'homepage.html')

i have created the "templates" directory under travellproj (please refer the directory structure below) also defined DIRS of template variable as below and urls.py as below.

"DIRS": [os.path.join(BASE_DIR,'templates')],

urlpatterns = [
    path("",views.homepage),
    path("admin/", admin.site.urls),
]

But I'm receiving a TemplateDoesNotExist error, please help.

Error

TemplateDoesNotExist at / homepage.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.5 Exception Type: TemplateDoesNotExist Exception Value:
homepage.html Exception Location: C:\Users\Django\first_proj\lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: travello.views.homepage

Directory structure:

travello
|-views.py
travellProj
|-templates -- > homepage.html
|-urls.py
|-setting.py

CodePudding user response:

Your templates folder should be at the root of your site. Let see how it should look like:

Project_folder
|-travelproj <-- Your site configuration folder
|-|-urls.py
|-|-wsgi.py
|-|-asgi.py
|-|-.......
|-travello <-- this is an application
|-|-views.py
|-|-urls.py
|-|-templates <-- templates for this app only
|-|-|-travello
|-|-|-|-template1.html
|-|-|-|-.......
|-|-.......
|-templates <- This is the templates folder for your site
|-|-homepage.html
|-|-..........
|-manage.py
|-requirements.txt

So in your case your templates folder is in your site configuration folder which is not a good practice. you have to move it one step higher.

Good practices tips: At the root of your site (same level than manage.py) you have a templates folder which will contain the templates commons to all your applications. In each application you have a folder templates/app_name which contain all the templates specifics for this application.

You have the same architecture for statics.

CodePudding user response:

Inside templates create another new directory by your app name travello then keep the html file inside the travello directory

travello
| templates/travello/homepage.html
|-views.py
travellProj
|-urls.py
|-setting.py

Then views should be like

def homepage(request):
    return render(request,'travello/homepage.html')
  • Related