[PYTHON] [Day 5] View and template basics

January 10, 2021 ← Last time: Create Day 4 application

The theme this time is "Basics of Views and Templates". Until now, you may not have been able to realize the fun of Django with only detailed setting work. Finally, we will output HTML for a specific URL. Hello World First of all, let's output the characters on the screen, both in the rabbit and in the corner.

python



#This is a familiar one
$ source venv/bin/activate 
(venv)$ cd ./mysite/base
(venv)$ emacs views.py

Add views.py for base.

base/views.py


from django.http import HttpResponse
from django.template import loader

def top(request):
    return HttpResponse('Hello World')

Modify base/urls.py to associate the top function added to this views.py with the URL.

base/urls.py


from django.urls import path
from . import views
name = 'base'

urlpatterns = [
    path('', views.top, name='top'),
]

Let's check it with a browser.


(venv)$ python manage.py runserver 8080

You should now see Hello World in your browser.

Set the templates directory

First, rewrite the settings in the TENPLATES part of settings.py.

mysite/settings.py


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

Create a templates directory directly under the project and create a base directory in it.

#image
mysite
   └─templates
   |    └─base
   |
   └─mysite

It's hard to understand because there are two mysites, but templates is the above directory. If it is difficult to understand, you may change the project name.

(venv)$ cd mysite #Move if not directly under the project
(venv)$ mkdir -p mysite/templates/base

Try to make a template

base Generates a template file for your application.

mysite/templates/base/top.html



<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="content-language" content="ja">
    <title>{{title}}</title>
</head>
<body>
<h1>{{title}}</h1>
<p>Template test display</p>
</body>

Rewrite the top function in base/views.py to use the template as follows.

base/views.py


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

def top(request):
    template = loader.get_template('base/top.html')
    ctx = {'title': 'Django learning channel(Temporary)'}
    return HttpResponse(template.render(ctx, request))

Let's check the browser.


(venv)$ python manage.py runserver 8080

You should see it like this. Please do not dig into the name sense. I refer to the Dango study book blog as it is, so ... スクリーンショット 2021-01-10 11.54.13.png

It was confirmed that the title parameter passed in views.py was passed to the template. Django templates are displayed by passing parameters as dict type variables and enclosing the parameter names in "{{}}" on the template side.

Well, it was displayed, but every time it is displayed in the template, it is troublesome to load and display the template as before, so a shortcut is prepared. The previous views.py can be rewritten as follows.

base/views.py



from django.shortcuts import render
# from django.http import HttpResponse
# from django.template import loader

def top(request):
    # template = loader.get_template('base/top.html')
    ctx = {'title': 'Django learning channel(Temporary)'}
    # return HttpResponse(template.render(ctx, request))
    return render(request, 'base/top.html', ctx)    

Neither loader nor HttpResponse is required, so you can write clearly. You can use render to display any template by passing the context (think of it as a container for passing variables to the template).

in conclusion

This time I created the basis of the template. At first, the location of templates was ./mysite/mysite/templates and I was suffering from errors for about an hour. I'm glad that it was finally resolved.

See you again

← Last time: Create Day 4 application → Next time: Handle Day6 static files

Recommended Posts

[Day 5] View and template basics
[Day 7] Template inheritance and include
Perceptron basics and implementation
Python basics: conditions and iterations
Search basics and Java implementation / measurement
View photos in Python and html
Image recognition environment construction and basics
Read "Basics of Quantum Annealing" Day 6
Open3D basics and point cloud voxels