This is Ponta, a Shiba Inu. The other day I was chatting with my online friends pretending to be human, but I started to think that the other person might be a dog pretending to be human. I wonder if I should come out.
Well, today I'm going to challenge Django templates. A template is a web page HTML with variables and processes embedded in it, and creates a screen to insert and display values here.
Create folders templates, templates / wan under the directory wan, and a template file index.html under templates / wan. The tree looks like this.
(venv_dog) Ponta@shiba_app # tree
.
// ...abridgement
└── wan
// ...abridgement
├── templates
│ └── wan
│ └── index.html
// ...abridgement
The template index.html was written as follows.
wan/templates/wan/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<p>{{ year }}Year{{ month }}Month{{ date }}Day</p>
<p>{{ description }}</p>
</body>
</html>
Put the variable inside {{}}. Here the variables are title, year, month, date, description.
The template is called from views.py, so rewrite views.py as follows.
wan/views.py
from django.shortcuts import render
def index(request, dogname, diarydate):
year = diarydate[:4]
month = diarydate[4:6]
date = diarydate[6:]
title = dogname + "s diary"
description = "Today's rice is yakiniku!"
params = {
'year': year,
'month': month,
'date': date,
'description': description,
'title': title,
}
return render(request, 'wan/index.html', params)
Originally, the procedure would be to call the template with django.template.loader.get_template ('wan / index.html'), set the template variables with the render function, and then return the HttpResponse object as before. But thankfully Django has a render () function for the shortcut, so I'm using it.
The render () function takes three arguments, a request object, a template name, and a parameter, renders it, and returns an HttpResponse object. [^ 1]
In Django, when you use a template, you need to register the application to be used in the project. Therefore, register the app wan in the variable INSTALLED_APP described in shiba_app / settings.py.
shiba_app/settings.py
// ...abridgement
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'wan',
]
// ...abridgement
The last line ('wan',) is added.
Let's display it.
Yesterday's rice was yakiniku. I'm a dog, so I don't need sauce. See you dear! one!
[^ 1]: Create your first Django app, part 3 Write a view that actually works
Recommended Posts