程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The fifth meeting of Django framework

編輯:Python

List of articles

  • Django The fifth meeting of the framework
    • Template syntax passing values
    • Filter of template syntax
    • Label of template syntax
    • Custom filter 、 label 、inclusion_tag
    • Inheritance of templates
    • Template import

Django The fifth meeting of the framework

Template syntax passing values

  • effect : Template syntax can be passed to the back end python data type

In template syntax :

  • Variable correlation : { { }}
  • Logical correlation : {% %}

Use of template syntax

  1. views.py
def index(request):
n = 123
f = 11.22
s = ' character string '
b = True
l = ['tom', 'jack', 'maria']
t = (11, 22, 33)
d = {
'username': 'tony', 'age': 18, 'info': ' There's something '}
se = {
' Ice mound ', ' Snow Rongrong '}
def func():
return ' Function return value '
class MyClass(object):
def get_self(self):
return 'resl'
@staticmethod
def get_func():
return 'func'
@classmethod
def get_class(cls):
return 'class'
def __str__(self):
return ' Double down str Method '
obj = MyClass()
return render(request,'index.html',locals())
  1. Front page
 <p>{
{
 n }}</p>
<p>{
{
 f }}</p>
<p>{
{
 s }}</p>
<p>{
{
 b }}</p>
<p>{
{
 l }}</p>
<p>{
{
 d }}</p>
<p>{
{
 t }}</p>
<p>{
{
 se }}</p>
<p>{
{
 func }}</p>
<p>{
{
 MyClass }}</p>
<p>{
{
 obj }}</p>
<p>{
{
 obj.get_self }}</p>
<p>{
{
 obj.get_class }}</p>
<p>{
{
 obj.get_func }}</p>
  1. Display the results

  1. Summary and supplement :
  1. python All data types of , Can use template syntax , Pass to the front page
  2. function 、 Classes and objects When using template syntax , It will automatically identify whether it can be executed , What can be executed will be added automatically () call , The result shown is the return value ( Adding parentheses to classes and objects will automatically trigger double down str Method )
  3. function 、 Classes and objects , Passing additional parameters is not supported .
  4. Django The value of template syntax Has a fixed format Only use “ Local character
<p>{
{
 d.username }}</p>
<p>{
{
 l.0 }}</p>
<p>{
{
 t.1}}</p>
# And you can click both keys and indexes You can also mix the two 
eg: {
{
 d.hobby.3.info }}


Filter of template syntax

  • A filter can have at most two parameters
  • Filter class is a built-in method based on template syntax
  • Django Built in 60 Multiple filters This is just an introduction 10 about

Basic grammar :

{ { data | filter : Parameters }}

  1. The front-end code
<p> Statistical length :{
{
 s|length }}</p>
<p> The default value is :{
{
b|default:' Nothing ' }}</p>
<!-- When the Boolean value of the first parameter is True when , Just show the value of the first parameter, otherwise show the value after the colon -->
<p> file size :{
{
 file_size|filesizeformat }}</p>
<!-- Automatically according to file_size Replace the corresponding unit with the value of file_size Is the variable name defined by the backend -->
<p> Date formatting :{
{
 current_time|date:'Y-m-d H:i:s' }}</p>
<!-- current_time The time of backend acquisition -->
<p> Slicing operation ( Support step size ):{
{
 l|slice:'0:4:2' }}</p>
<p> Cut characters ( The specified length contains three points ):{
{
 info|truncatechars:9 }}</p>
<p> Cut the words ( The specified length does not contain three points Cut by space ):{
{
 egl|truncatewords:9 }}</p>
<p> Remove specific characters :{
{
 egl|cut:' ' }}</p>
<p> Splicing operation :{
{
 l|join:'$' }}</p>
<p> Splicing operation ( Add ):{
{
 n|add:10 }}</p>
<p> Splicing operation ( Add ):{
{
 s|add:s}}</p>
<!-- Pay attention to the method : escape Template syntax does not support escape by default At the front end, you need to add safe Parameter can be escaped It can also be processed at the back end -->
<p> escape : {
{
 h1 }}</p>
<p> escape : {
{
 h1|safe }}</p>
<p> escape ( The back-end processing ): {
{
 h2 }}</p>
  1. Back end supplementary code
file_size = 213123
current_time = datetime.datetime.utcnow()
info = ' List of articles Django Framework's fourth handshake routing distribution namespace pseudo static virtual environment Django Version difference view layer three board axes JsonResponse object form Form upload file request Object methods FBV and CBVCBV Source code analysis summary Django The fourth handshake routing distribution of the framework Django box '
egl = 'my name is UPythonFish my age is 18 i like python'
h1 = '<h1>h1 label </h1>'
# Back end escape 
from django.utils.safestring import mark_safe
h2 = mark_safe('<h2>h2 label </h2>')
  1. Display the results

Label of template syntax

  • Tags are a bunch of logic , Include for loop if Judgment, etc
1. for loop
{
% for foo in l %}
<p>{
{
 forloop }}</p> <!--fooloop It's a built-in variable fooloop.first Only the first is true fooloop.last Only the last time was true-->
<p>{
{
 foo }}</p> <!--foo Is a value in an iteratable object -->
{
% endfor %}
2. if Judge
{
% if b %}
<p> Small baby</p>
{
% elif ' word ' in s %}
<p> in baby</p>
{
% else %}
<p> Big baby</p>
{
% endif %}
3. for And if A mixture of
{
{
% for foo in l %}
{
% if forloop.first %}
<p> This is my first time </p>
{
% elif forloop.last %}
<p> This is the last time </p>
{
% else %}
<p>{
{
 foo }}</p>
{
% endif %}
{
% empty %}
<p>empty Only in for There are no elements inside the iteratable object of the loop There is no way to trigger when the loop </p>
{
% endfor %}
4. Other ways to deal with dictionaries
# Take out key value 
{
% for foo in d.keys %}
<p>{
{
 foo }}</p>
{
% endfor %}
# Extract value 
{
% for foo in d.values %}
<p>{
{
 foo }}</p>
{
% endfor %}
# Take out the key value pair Tuple form 
{
% for foo in d.items %}
<p>{
{
 foo }}</p>
{
% endfor %}
5. with names
{
% with d.hobby.3.info as nb %}
<p>{
{
 nb }}</p>
<p> stay with Grammar can be passed through as The following aliases are quickly used in the very complicated way to obtain data </p>
<p>{
{
 d.hobby.3.info }}</p>
{
% endwith %}

Custom filter 、 label 、inclusion_tag

Be careful :

  1. Custom filter 、 label 、inclusion_tag when , must First, create an application templatetags Folder
  2. Create a folder with any name in the folder py file eg: mytag.py
  3. In the py In the file must First write the following two sentences ( Not one word can be wrong )
from django import template
register = template.Library()

Custom filter :

@register.filter(name='f1')
def my_sum(v1, v2):
return v1 + v2
Front end use :
{
% load mytag %}
<p>{
{
n|f1:210}}</p>

Custom tag :

 Custom tags are similar to custom functions , Can have multiple parameters
@register.simple_tag(name='tag1')
def index(a, b, c, d):
return '%s-%s-%s-%s' % (a, b, c, d)
Front end use :
{
% load mytag %}
Multiple parameters of the tag are separated from each other by spaces
<p>{
% tag1 123 123 123 123 %}</p>

Customize inclusion_tag:

  1. internals

    Let's define a method , Call this method on the page , And it can transfer values

    This method generates some data and passes it to a html page

    After that, put the rendered result in the call position

@register.inclusion_tag('left_menu.html')
def left(n):
data = [f' The first {
i} term ' for i in range(n)]
# The first method of value transfer 
# return {'data':data}
# The second method of value transfer 
return locals()
left_menu.html
<ul>
{
% for foo in data %}
<li>{
{
 foo }}</li>
{
% endfor %}
</ul>
Front end use
{
% load mytag %}
{
% left 10 %}

summary : When html A page somewhere in the page needs to pass parameters before it can be dynamically rendered , And this part needs to be used on multiple pages Then consider changing the local page into inclusion_tah form

Inheritance of templates

  • Template inheritance refers to Select a template page you want to inherit first, and then the sub page inherits the template page , Just delimit the area that can be modified on the template page in advance , The sub page can declare that you want to modify the delimited area , And make changes
  • Generally, the template page should have at least three areas that can be modified css Area html Area js Area

Implementation of template inheritance :

  1. Template page creation (home.html)

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    {
    % block css %}
    {
    # Customize css Pattern area #}
    {
    % endblock %}
    </head>
    <body>
    <nav class="navbar navbar-inner">
    <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    </div>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
    <li><a href="#">Link</a></li>
    <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
    <ul class="dropdown-menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li role="separator" class="divider"></li>
    <li><a href="#">Separated link</a></li>
    <li role="separator" class="divider"></li>
    <li><a href="#">One more separated link</a></li>
    </ul>
    </li>
    </ul>
    <form class="navbar-form navbar-left">
    <div class="form-group">
    <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
    </form>
    <ul class="nav navbar-nav navbar-right">
    <li><a href="#">Link</a></li>
    <li class="dropdown">
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
    <ul class="dropdown-menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li role="separator" class="divider"></li>
    <li><a href="#">Separated link</a></li>
    </ul>
    </li>
    </ul>
    </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
    </nav>
    <div class="container-fluid">
    <div class="row">
    <div class="col-md-4">
    <div class="list-group">
    <a href="/home/" class="list-group-item active"> home page </a>
    <a href="/login/" class="list-group-item"> Sign in </a>
    <a href="/reg/" class="list-group-item"> register </a>
    </div>
    </div>
    <div class="col-md-8">
    <div class="jumbotron">
    {
    % block content %}
    {
    # Customize the main page content area #}
    <h1>Hello, world!</h1>
    <p>...</p>
    <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
    {
    % endblock %}
    </div>
    </div>
    </div>
    </div>
    {
    % block js %}
    {
    # Customize js Code area #}
    {
    % endblock %}
    </body>
    </html>
    
  2. Subpage inheritance

    1. login.html
    {
    # Inherit template page #}
    {
    % extends 'home.html' %}
    {
    # Modify what you want to modify #}
    {
    % block content %}
    <h1> The login page </h1>
    <form action="">
    <p>username:<input type="text" class="form-control"></p>
    <p>password:<input type="text" class="form-control"></p>
    <input type="submit" value=" Sign in " class="btn btn-block btn-success">
    </form>
    {
    % endblock %}
    2. reg.html
    {
    # Inherit template page #}
    {
    % extends 'home.html' %}
    {
    # Modify what you want to modify #}
    {
    % block content %}
    <h1> Registration page </h1>
    <form action="">
    <p>username:<input type="text" class="form-control"></p>
    <p>password:<input type="text" class="form-control"></p>
    <input type="submit" value=" register " class="btn btn-block btn-danger">
    </form>
    {
    % endblock %}
    
    1. Realization effect

Template import

  • Treat a part of the page as a module , That place can be directly imported and used if necessary
{
% include 'muban.html'}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved