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:
- create a
templates
directory in theapp
directory (i.e:app/templates/app/template_name.html
) - Or, create a
templates
folder in theproject
directory (i.e:templates/template_name.html
ortemplates/app/template_name.html
), if you choose to go with this option, you'll have to pointdjango
to this directory by updating youTEMPLATES
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",
],
},
},
]
- Then , in your views, specify the path to your
.html
file(s)
Example:
- With option 1: the path will be
app/template_name.html
- With Option 2: the path will be
template_name.html
orapp/template_name.html
(depends on your folder structure)