A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template

About this article

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.

Setting the location of the template file

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 image.png

I will explain in detail step by step.

    1. Create a folder called templates under first \ myapp.
  1. Furthermore, create a folder with the same app name (myapp this time) under it.
    1. Create index.html in that myapp folder.
  2. If you access myapp / index.html in urls.py, you will be accessing this index.html file.
  3. It may be good to remember that it is saved according to the rules like ↓. / / templates /

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.

Operation check

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.

image.png

Next article

https://qiita.com/sw1394/items/4bc6349dd3a32938dcaf

Recommended Posts

A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
A super introduction to Django by Python beginners! Part 3 I tried using the template file inheritance function
A super introduction to Django by Python beginners! Part 6 I tried to implement the login function
A super introduction to Django by Python beginners! Part 4 I made a super-simple diary application (created only with functions without using a class-based general-purpose view)
A super introduction to Django by Python beginners! Part 1 I tried to display an HTML page that only says "Hello World"
A super introduction to Django by Python beginners! Part 5 I made a super simple diary application with a class-based general-purpose view
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
I tried to make a regular expression of "date" using Python
I tried to verify and analyze the acceleration of Python by Cython
I tried to verify the result of A / B test by chi-square test
I tried to analyze the New Year's card by myself using python
I tried using the Datetime module by Python
[Python] I tried to judge the member image of the idol group using Keras
I made a script to record the active window using win32gui of Python
Cut a part of the string using a Python slice
I tried to erase the negative part of Meros
I tried using Python (3) instead of a scientific calculator
I tried to summarize the string operations of Python
Introduction to AI creation with Python! Part 2 I tried to predict the house price in Boston with a neural network
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
Python practice 100 knocks I tried to visualize the decision tree of Chapter 5 using graphviz
I tried to find the entropy of the image with python
I tried to make a function to retrieve data from database column by column using sql with sqlite3 of python [sqlite3, sql, pandas]
[Python] I tried to visualize the follow relationship of Twitter
[Python] I tried collecting data using the API of wikipedia
I tried to make a stopwatch using tkinter in python
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
I tried to compare the accuracy of machine learning models using kaggle as a theme.
What seems to be a template of the standard input part of the competition pro in python3
I tried to create a Python script to get the value of a cell in Microsoft Excel
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
I tried to automate the construction of a hands-on environment using IBM Cloud's SoftLayer API
I wrote a class that makes it easier to divide by specifying part of speech when using Mecab in python
I tried to get a database of horse racing using Pandas
I tried to get the index of the list using the enumerate function
[Introduction to Python] I compared the naming conventions of C # and Python.
[Introduction to simulation] I tried playing by simulating corona infection ♬ Part 2
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
I tried to create a list of prime numbers with python
I tried to get a list of AMI Names using Boto3
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I tried to make a todo application using bottle with python
I tried to improve the efficiency of daily work with Python
I tried to verify the speaker identification by the Speaker Recognition API of Azure Cognitive Services with Python. # 1
I tried to verify the speaker identification by the Speaker Recognition API of Azure Cognitive Services with Python. # 2
I tried to summarize the contents of each package saved by Python pip in one line
[Python] I tried to make a simple program that works on the command line using argparse.
A super introduction to Python bit operations
The Python project template I think of.
I tried to transform the face image using sparse_image_warp of TensorFlow Addons
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
I tried to get the batting results of Hachinai using image processing
I tried to communicate with a remote server by Socket communication with Python.
I tried to estimate the similarity of the question intent using gensim's Doc2Vec
[Introduction to Python] How to sort the contents of a list efficiently with list sort
I tried to get the authentication code of Qiita API with Python.
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~
I want to color a part of an Excel string in Python
I tried to find the optimal path of the dreamland by (quantum) annealing
I tried to extract and illustrate the stage of the story using COTOHA