current position:Home>Daily python, chapter 27, Django template
Daily python, chapter 27, Django template
2022-02-01 13:38:46 【Qing'an slag】
This is my participation 11 The fourth of the yuegengwen challenge 27 God , Check out the activity details :2021 One last more challenge 」
This is Qing'an , Learn a little every day , Today is no exception .V:qing_an_an
Django The template in controls the static state of the front end ⻚⾯,⼀ Complete web Should be ⽤ Front end static data is indispensable .
First, you have to prepare your own application . The preparation process is no longer mentioned here .
Create a template file for managing templates .
templates:
It can be put in the application , It can also be placed outside the application , As long as it is in the project .
The file name is fixed , You can't change it at will . In this file, we create a template , The template is HTML5 Format .
Here because I wrote it in advance , So there are five HTML Template out . But on the right body Content can be added .
Next, we write the code content in the view in the application :
# Whether you create a model or a template, you return resources to the route through the view
def hello(request):
return render(request, "hello.html")
Copy code
If you are more careful here, you will ask , In front of it is HttpResponse, It's used here render, Because there are templates here .
Read my notes carefully , Both models and templates return resources to routes through views , Next, we need to add a path to the route .
from testapp.views import *
urlpatterns = [
path('hello/',hello),
]
Copy code
The import here *, By default, all items in the view are imported , This is easier , You don't need to write one, import one .
Next run Django The code can be ,python manage.py runserver:
Here you can see that the content in the view is presented in the browser .
Dictionary value
The default value specified in the template is directly passed here , If you pass in a dictionary , If you want to present the above words in the form of key value pairs, how should you write them .
View writing :
def hello1(request):
data = {'key1': 'Hello', 'key2': 'QingAn', 'key3': '!'}
return render(request, "hello1.html", data)
Copy code
The route changes slightly :
from testapp.views import *
urlpatterns = [
path('hello1/',hello1),
]
Copy code
Template writing :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<p>
{{key1}} {{key2}} {{key3}}
</p>
</body>
</html>
Copy code
Use two curly braces to receive the passed value , In this way, you can get the above word effect .
Dictionary list transfer value
View writing :
def hello2(request):
data = {'key':['Hello', 'Qing', 'An', '!']}
return render(request, "hello2.html", data)
Copy code
The route changes slightly :
from testapp.views import *
urlpatterns = [
path('hello2/',hello2),
]
Copy code
Template writing :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<p>
{{ key.0 }} {{ key.1 }} {{ key.2 }} {{ key.3 }}
</p>
</body>
</html>
Copy code
The value here is similar to the subscript value in the list . Run by yourself to see the effect , The contrast picture, such as the picture pasted at the beginning, has the same effect .
The dictionary is embedded in the dictionary to pass values
View writing :
def hello3(request):
data = {'key': {'key1': 'Hello !', 'key2': 'Qing', 'key3': 'An'}}
return render(request, "hello3.html", data)
Copy code
The route changes slightly :
from testapp.views import *
urlpatterns = [
path('hello3/',hello3),
]
Copy code
Template writing :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<p>
{{ key.key1 }} {{ key.key2 }} {{ key.key3 }}
</p>
</body>
</html>
Copy code
This is similar to dot passing value , Point to point matching .
Yes or no
When we were testing the front end , I occasionally see such a scene , Click Yes and it will become No , Clicking again will change from no to yes , How can this be realized . Let's simply implement today :
View code :
def hello4_if(request):
num = random.randint(0, 1) # Generate a random integer from a given
return render(request, "hello4.html", {'num': num})
Copy code
Routing code :
from testapp.views import *
urlpatterns = [
path('hello4/',hello4),
]
Copy code
Template code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<p>
{% if num > 0 %}
yes
{% else %}
no
{% endif %}
</p>
</body>
</html>
Copy code
Here we generate random numbers , Used to judge , There are views that return results to the template , The template then makes its own judgment , Yes and no are output . Effect browse by yourself .
for loop
View code :
def hello5_for(request):
list = ['Hello', 'World']
# Only receive dictionaries
return render(request, "hello5.html", {'key': list})
Copy code
Routing code :
from testapp.views import *
urlpatterns = [
path('hello5/',hello5),
]
Copy code
Template code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<p>
{% for foo in key %}
{{ foo }}
{% endfor %}
</p>
</body>
</html>
Copy code
So you can cycle through the values in the list . The code in the template is similar to python Medium for loop , It's just that the format of writing code is different . So you need to This is the point of attention .
The other is , Every time I pass the following values in the form of a dictionary , So this is also a point of attention !
copyright notice
author[Qing'an slag],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011338451257.html
The sidebar is recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
guess what you like
-
Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
-
Python -- datetime (timedelta class)
-
Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
-
[Python] comparison of dictionary dict, defaultdict and orderdict
-
Test driven development using Django
-
Face recognition practice: face recognition using Python opencv and deep learning
-
leetcode 1610. Maximum Number of Visible Points(python)
-
Python thread 03 thread synchronization
-
Introduction and internal principles of Python's widely used concurrent processing Library Futures
-
Python - progress bar artifact tqdm usage
Random recommended
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)
- Python data analysis - linear regression selection fund
- How to make a python SDK and upload and download private servers
- Python from 0 to 1 (day 20) - basic concepts of Python dictionary
- Django -- closure decorator regular expression
- Implementation of home page and back end of Vue + Django tourism network project
- Easy to use scaffold in Python
- [Python actual combat sharing] I wrote a GIF generation tool, which is really TM simple (Douluo continent, did you see it?)
- [Python] function decorators and common decorators
- Explain the python streamlit framework in detail, which is used to build a beautiful data visualization web app, and practice making a garbage classification app
- Construction of the first Django project
- Python crawler actual combat, pyecharts module, python realizes the visualization of river review data
- Python series -- web crawler
- Plotly + pandas + sklearn: shoot the first shot of kaggle
- How to learn Python systematically?
- Analysis on several implementations of Python crawler data De duplication
- leetcode 1616. Split Two Strings to Make Palindrome (python)
- Python Matplotlib drawing violin diagram
- Python crawls a large number of beautiful pictures with 10 lines of code
- [tool] integrated use of firebase push function in Python project
- How to use Python to statistically analyze access logs?