Home > other >  Why is Django saying my template doesn't exist even though it does?
Why is Django saying my template doesn't exist even though it does?

Time:10-27

I'm a beginner following this Django tutorial (https://www.w3schools.com/django/django_templates.php) and I'm getting the error bellow after making the html template and modifying the views.py file (name erased for privacy):


Internal Server Error: /members
Traceback (most recent call last):
  File "C:\Users\\myproject\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\\myproject\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\\myproject\myworld\members\views.py", line 5, in index
    template = loader.get_template('myfirst.html')
  File "C:\Users\\myproject\lib\site-packages\django\template\loader.py", line 19, in get_template
    raise TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: myfirst.html
[26/Oct/2022 16:51:01] "GET /members HTTP/1.1" 500 64964


Tried this:

from django.http import HttpResponse
from django.shortcuts import loader

def index(request):
    template = loader.get_template('myfirst.html')
    return HttpResponse(template.render())


Expecting this:


   <!DOCTYPE html>
   <html>
   <body><h1>Hello World!</h1>
   <p>Welcome to my first Django project!</p>
   </body>
   </html>

CodePudding user response:

first, you have to create a templates folder, then create into it your HTML file "myfirst.html", then create your HTML tags in it, for example:

<h1>Hello, World</h1>

CodePudding user response:

Create a directory where your .html will live:

  1. create a templates directory in the app directory (i.e: app/templates/app/template_name.html)
  2. Or, create a templates folder in the project directory (i.e: templates/template_name.html or templates/app/template_name.html), if you choose to go with this option, you'll have to point django to this directory by updating you TEMPLATES setting
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        # Add path to templates
        "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",
            ],
        },
    },
]
  1. Then , in your views, specify the path to your .html file(s)

Example:

  1. With option 1: the path will be app/template_name.html
  2. With Option 2: the path will be template_name.html or app/template_name.html (depends on your folder structure)
  • Related