This is the output page of the result of learning about Django on Udemy. This is a continuation of the previous article . This time, I'm going to use render, which is one of Django's features.
urls.py ulrs.py is the same as last time.
first\myapp\urls.py
from django.urls import path
from . import views
app_name = 'myapp'
urlpatterns = [
path('', views.index, name='index'),
]
views.py Modify views.py as follows.
first\myapp\views.py
from django.shortcuts import render
def index(request):
context = {
'names':['Suzuki','Sato','Takahashi'],
'message':'Hello.',
}
return render(request, 'myapp/index.html', context)
First, import the render with from django.shortcuts import render
.
Next, edit the def index. Add a dictionary called context to the def index. The context has a key called names and message. Let's register multiple values for names.
Finally, pass the context to myapp / index.html with return render (request,'myapp / index.html', context)
.
The context Key and value are now available in myapp / index.html.
Django has a fixed location for template files.
It's pretty confusing when this area starts learning Django, In conclusion, myapp / index.html is in the following location. first\myapp\templates\myapp\index.html
I will explain in detail step by step.
index.html Describe as follows in index.html.
first\myapp\templates\myapp\index.html
<p>{{ names.0 }}Mr.{{ message }}</p>
<p>{{ names.1 }}Mr.{{ message }}</p>
<p>{{ names.2 }}Mr.{{ message }}</p>
<hr>
{% for name in names %}
<p>{{ name }}Mr.{{ message }}</p>
{% endfor %}
The description you write in a Django HTML file seems to be similar to Python, but with a slightly different notation.
Enclose variables in {{}}
and program instructions such as for in {%%}
.
Also, since there is no concept of indentation in HTML, it is necessary to express it explicitly with {% endfor%}
at the end of for and if.
If you're used to Python, it can be quite annoying, but you have to get used to it.
I will explain from the first three lines.
Three values were registered in the names of context.
names.0
means pulling the first value of names.
names.1
is the second value for names.
No subscript is required because message
has only one value.
Next, I will explain the last three lines.
With {% for name in names%}
, retrieve the values one by one from names.
This area has the same notation as Python, so it's easy to understand.
Don't forget to close it with {% endfor%}
at the end.
Let's start the development server with py manage.py runserver and access index.html. If it is displayed as below, there is no problem. The upper three lines are the value display with subscripts, and the lower three lines are the value display with for minutes.
https://qiita.com/sw1394/items/4bc6349dd3a32938dcaf
Recommended Posts