Djangos basic views function

“This is the second day of my participation in the Gwen Challenge.

Views CBV and FBV

FBV

FBV function based viewCopy the code

CBV

Class based view, using the interviewer-based approach is CBVCopy the code
from django.views import View

class xxx(View) :
    def dispatch(self, request, *args, **kwargs) :
    	return super().dispatch(request, *args, **kwargs)# actually
    
    def get(self,request) :
    	# Handle get requests exclusively
        return response
    
    def post(self,request) :
    	# Handle POST requests exclusively
        return response
Copy the code
url(r"xx/",xxx.as_view()) As_view () is executed
Copy the code
As_view () process
1. The project runtime loads the urls.py file and executes the class with the as_view() method. 2. 1. Instantiate the class --> self 2. self. Request = request 3. Execute self.dispath(request,*args,**kwargs) method 1. Check whether the request method is allowed. 1. Allow: - Obtain the request method corresponding to the request method by reflection -->handler. Not allowed :- self. http_not_allowed -->handler 2. Execute hanlder and return the resultCopy the code
# http_method_names = ['get'] # Http_method_names overwrites submitted request methods that are called first when the View function is executed internally
def dispatch(self, request, *args, **kwargs) :
    print("Operation before dispatch")
    ret = super().dispatch(request, *args, **kwargs)Execute the dispatch method inside the View
    print("Operation after dispatch")
    return ret
Copy the code

CBV executes the Dispatch method before running the GET and POST methods

Use process CBV

1. Write the url url (r ^ "books / $", views. Books. As_view ()), 2. Write method in view functionCopy the code
# url.py
urlpatterns = [
	url(r'^admin/', admin.site.urls),
    url(r"^books/$", views.books.as_view()),
]

# views.py
from django.views import View


class books(View) :

    def dispatch(self, request, *args, **kwargs) :
        print("1")
        func = super().dispatch(request, *args, **kwargs)
        print("2")
        return func

    def get(self, request) :
        # Handle get requests exclusively
        return render(request, "login.html")

    def post(self, request) :
        # Handle POST requests exclusively
        user = request.POST.get("user")
        password = request.POST.get("password")
        user_obj = models.User.objects.filter(username=user, password=password)
        if not user_obj:
            return render(request, "login.html")
        return render(request, "index.html")
Copy the code

FBV,CBV plus decorator

FBV plus decorator
I just add it to the functionCopy the code
CBV plus decorator

You need to use a decorator and import the package method_decorator

From django.utils.decorators import method_decorator@method_decorator converts a function decorator into a method decorator.Copy the code
  1. Plus the method
@method_decorator(timer)
def get(self, request) :   This is the only way to use the get method
Copy the code
2. Add to the dispatch methodCopy the code
 @method_decorator(timer)  All of the request methods defined in # can be used
    def dispatch(self, request, *args, **kwargs) :
        print("Operation before dispatch")
        ret = super().dispatch(request, *args, **kwargs)Execute the dispatch method inside the View
        print("Operation after dispatch")
        return ret
Copy the code
3. Add to the classCopy the code
@method_decorator(timer,name="get")
@method_decorator(timer,name="post")
@method_decorator(timer,name="dispatch")
class PublishersAdd(View) :	# add to class, you can specify the corresponding method
Copy the code

Decorator: timer

# Count time decorator
import time
from functools import wraps

def timer(func) :
    @wraps(func)
    def inner(*args, **kwargs) :
        "" inner function ""
        start = time.time()
        ret = func(*args, **kwargs)
        print("Total execution time :{}".format(time.time() - start))
        return ret

    return inner

@timer
def func() :
    """ I'm a func function """
    time.sleep(0.5)
    print("aaaa")

func()
print(func.__name__)  # Wraps (@wraps(func)) # wraps(@wraps(func))
print(func.__doc__) Print comments in the function
Copy the code
from functools import wraps
@wraps(func) Use # wraps to render your own wraps, and comments, otherwise it would render wraps inside the inner wraps
Copy the code

Request (for)

Method Request method GET POST Request.GET Parameters carried in the URL? K1 =v1$k2=v2 {} Request. POST The data submitted in the POST request is encoded by URLencode request.path_info The path information does not contain the IP address, port, or parameters /publisher_list/ Request. body The body of the request, Byte Request. POST data is extracted from the body (the content submitted by the POST request is retrieved) request.COOKIES COOKIES Request. session Sessions are similar to dictionary objects Request. FILES Uploaded FILES Information in the request.META header lowercase --> uppercase HTTP_ Uncommon attributes: Request.scheme () HTTP or HTTPS Request. path() Specifies the requested path component (excluding the domain name).Copy the code
Common methods: request.get_full_path() The complete path information does not contain IP and port, including the request.is_ajax() parameter whether the request is an Ajax requestCopy the code

Response = response

from django.shortcuts import render, HttpResponse, redirect

HttpResponse("String")  # return string
render(request,"Template file name", {'k1':v1})  Return an HTML page
redirect('address') # redirection gives Location 'address' and status code 301 302
Copy the code
from django.http import JsonResponse

def text_json(request) :
    a = {"a":"b"}
    b = ["aa"."bb"]
    return JsonResponse(b,safe=False)  # safe=False to pass the list
Copy the code

Djangos basics — template syntax

Common template syntax

Render (request,” template filename “,{“k1″:” XXX “}) # render(request,” template filename “,{“k1″:” XXX “}

  1. There are only two special notations to remember in a Django template:

    1.1 {{}} and {% %}

    1.2 {{}} represents variables, which are replaced by values during template rendering, and {% %} represents logically related operations.

  2. Dot (.) It has a special meaning in template language and is used to obtain the corresponding attribute value of an object

Numeral :{{num}}<br>String :{{string}}<br>Dictionary: {{name_dict}} - > {{name_dict. Keys}} - > {{name_dict. Values}} - > {{name_dict. Name}}<br>{{name_list} --> {{name_list.2}}<br>Set :{{set} --> {{set.1}}<br>Tuple :{{tup}} --> {{tup.0}}<br>Class: {{person}} - > {{person. Name}} - > {{person. Talk}}Copy the code
Index.key.attribute. Method (method not followed by parentheses) Priority:.key >. Property.method >.indexCopy the code

The filter

Filter syntax: {{value | filter_name: parameter}}

Use the pipe “|” to apply the filter.

  1. Filters: Filters
 return render(request,"template_text.html", {"new_num":""{{}) | variable filter:"Parameters"Default:}} variable doesn't exist or use the default value is empty, if the value value didn't pass it shows nothing {{new_num | default:"2" }}
Copy the code
  1. filesizeformat
Format values to a "human-readable" file size (e.g. '13 KB', '4.1 MB', '102 bytes', etc.)

return render(request, "template_text.html", {"value": 1024 * 1024 * 1024})

{{ value|filesizeformat }}  # filesizefomrat: 1.0 GB
Copy the code
  1. add +
For variables and parameters of digital addition, string, and list of joining together the add: {{value2 | add:"2"}} - > list together: {{name_list | add: name_list}}# add: 4 - > list together: [' zhang ', 'bill', 'Cathy', 'zhang', 'bill', 'Cathy']
Copy the code
  1. lower,upper,title
Uppercase lowercase: {{value | lower}}, {{value | upper}} title: {{value | title}}# UppercaseCan write together: {{value | upper | lower | title}}Copy the code
  1. length
{{value | length}} returns the length of the value, such as value = ['a'.'b'.'c'.'d'] is displayed4.
Copy the code
  1. Slice slice
{{ name_list|slice:"0:2" }} [0:2]
Copy the code
  1. first,last
{{value:first}}  {{value.0}
{{value:last}}	 # take the last element
Copy the code
  1. Join string splicing
Use string concatenation lists. With pythonstr.join(list)。

{{ value|join:"__" }}  # Zhang SAN __ Li Four __ Wang five
Copy the code
  1. Truncatechars String interception
If the string has more than the specified number of characters, it is truncated. Truncated strings will be executed in a translatable ellipsis sequence ("..." End). Cutting parameters: the number of characters {{long_str | truncatechars:9 }} # include 3 ellipses Django...Truncatewords: Truncate according to the wordCopy the code
  1. Date Date formatting
import datetime
    now = datetime.datetime.now()
   
{{ now|date:"Y-m-d H:i:s" }}2020- 08-0810:17:14Or define the format directly in settings.py1. USE_L10N = False
	2.Set format: DATETIME_FORMAT ='Y-m-d H:i:s'
		TIME_FORMAT = 'H:i:s'DATE_FORMAT = 'y-m-d' and then directly: {{now}}, as aboveCopy the code
  1. safe
Django templates automatically escape HTML tags and javascript syntax tags for obvious reasons. For example:"safe_text":" Click me ", {{safe_text}} we get the string on the page :<a href='https://www.baidu.com'Let me < / a > > sometimes we don't want it, we can add a safe {{safe_text | safe}}# point I
Copy the code
  1. mark_safe
from django.utils.safestring import mark_safe

@register.filter
def show_b(name,url) :

    return mark_safe('<a href="{}">{}</a>'.format(url,name))  # You don't need to add safe when you use it
    
{{ "Baidu"|show_b:"http://www.baidu.com" }}
Copy the code

User-defined filter

  1. Create a Python package called TemplateTags in your app (the name of the package must be templateTags)

  2. Create a Python file with a custom filename (mytags.py)

  3. Create custom filters:

    from django import template
    
    register = template.Library()  The name # register can't be wrong
    
    @register.filter
    def add_arg(value, arg) : You can write only two parameters, one is a variable, one is a filter parameter
        # function
        return "__ {} {}".format(value, arg)
    Copy the code
    1. Use in HTML

    In the template:

    {% load mytags %} # with the load first loading mytags this file {{person. The name | add_arg: "I love you"}}Copy the code

Master and inheritance

The female version:

1. A common section containing multiple pages 2. Define multiple blocks to be overridden by sub-pagesCopy the code

Inheritance:

1. {% extends "master name" %} # xx.html {# leave template content #} {{block.super}}Copy the code
2. Rewrite block blocks (that is, blocks that overwrite the master)Copy the code

Note:

  1. {% extends “Master name” %} The name of the master is in quotes
  2. {% extends “master name” %} extends “master name” %} on the first line
  3. The content to be displayed is written to the block
  4. Write one more CSS \ JS block (because CSS \ JS cannot be exactly the same from page to page)

case

Create master: {% load static %}<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The motherboard</title>
    <style>
        div{
            width: 500px; height: 500px; border: 2px solid red;
        }
    </style>
     {% block css %} {% endblock %}  {# css#}
</head>
<body>
    <div>
        <a href="">What are you doing?</a>
    </div>{% block content %} {# content #} {% endblock %} {% block js %} {# js#} {% endblock %}</body>
</html>

Copy the code
{% extends "master.html" %} {% block CSS %}<style>
        div{
            background-color: blueviolet;
        }
    </style>
{% endblock %}

{% block content %}
    <h1>123321</h1>
{% endblock %}

{% block js %}

{% endblock %}
Copy the code

Components include

You can save commonly used page contents, such as navigation bars and end-of-page information, in a separate file, and then import them anywhere in the file according to the following syntax.Copy the code
  1. Write a small piece of common HTML text to an HTML file, nav.html

  2. Import in the template where the component is needed

    {% include 'nav.html' %}
    Copy the code

The sample

Create components<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>component</title>
    <style>* {list-style: none; margin: 0; padding: 0;
        }
        div{
            height: 50px; border: 1px solid red;
        }
        div ul li{
            width: 100px; height: 35px; border: 1px solid green; margin-left: 50px; float: left;
        }
    </style>
</head>
<body>
    <div>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
    </div>
</body>
</html>
Copy the code
{% extends "master.html" %} {% block CSS %}<style>
        div{
            background-color: blueviolet;
        }
    </style>
{% endblock %}

{% block content %}
    {% include "nav.html" %}
    <h1>123321</h1>
{% endblock %}

{% block js %}

{% endblock %}
Copy the code

The label tags

  1. for
<ul>
    {% for name in name_list %}
        <li>{{ forloop.counter }}-{{ name }}</li>
    {% endfor %}
</ul>
Copy the code

Some parameters available for the for loop:

Variable Description
forloop.counter Index value of the current loop (starting from 1)
forloop.counter0 Index value of the current loop (starting from 0)
forloop.revcounter Reverse index of the current loop (ending at 1)
forloop.revcounter0 Reverse index value of the current loop (ending at 0)
forloop.first Is the current loop the first (Boolean)
forloop.last Is the current loop the last (Boolean)
forloop.parentloop The outer loop of this layer’s loop

for … empty

{% for name in name_list2 %} <li>{{name}}</li> {% empty %}Copy the code
  1. if
{% elif value2 == 2 %} {% endif %}Copy the code

If statements support and, or, ==, >, <,! =, <=, >=, in, not in, is, is not judge.

Note:

  1. Arithmetic operations are not supported in conditions

  2. Continuous judgment is not supported

    {% if 5 > 4 and 4 > 1 %} ok {% else %} no {% endif %}Copy the code

with

That’s renaming

{% with name_list as name%} {{name}} {{name}} {% endwith %} or {% with name = name_list %} {{name}} {{name}} {% endwith %}Copy the code

User-defined tag simple_tag

  1. Create a templateTags folder in your app application folder, which must have this name;

  2. Create a xx.py file in the templateTags folder, and name it whatever you want.

  3. Creating a custom label

   from django import template
   
    register = template.Library()  # register fixed name
    @register.simple_tag
    def mytag(v1) :
     s = v1 + 'I love you'
        return s
   
    @register.simple_tag
    def mytag2(v1, v2, v3) :
        s = v1 + v2 + v3
        return s
Copy the code
  1. {% load te %} {% mytag s1 %} {% mytag2 s1 ‘yyz’ ‘lt’ %}

  2. Note: You can have more than one parameter.

inclusion_tag

Filter, simple_tag, inclusion_tag

There is no parameter limit

  1. Create a Python package called TemplateTags in your app (the name of the package must be templateTags)

  2. Create a Python file with a custom filename (mytags.py)

  3. Write in the Python package:

    from django import template
    
    register = template.Library()  The name # register can't be wrong
    Copy the code
    1. Write function + decorator
    filter:def add_arg(value,arg) : Only one parameter and value can be accepted
        return "xx"
    
    simple_tag:
    @register.simple_tag  Can accept multiple arguments and values
    def str_join(*args, **kwargs) :
        return "{} _ {}".format("-".join(args), "* * *"Inclusion_tag.join (kwargs)) :@register.inclusion_tag("page.html") Return the value to the page.html page
    def pagination(num) :
        return {'num': range(1, num + 1)}  Return a dictionary
    
    Copy the code
    1. use
    The filter: {% load mytags %} {% "alex" | add_arg: "I love you" %} simple_tag: {% load mytags %} {% str_join "a" "b" "c" k1 = "aa" k2 = "bb" %} {# a - b - c_k1 # * * * k2} inclusion_tag:  {% load mytags %} {% pagination 6 %}Copy the code

Instance (paging)

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

Method a #
@register.simple_tag
def pagination(num) :
    page_list = ['<li><a href="#">{}</a></li>'.format(i) for i in range(1,num+1)]
    print(page_list)
    return mark_safe(""" 
      """.format(' '.join(page_list)))


Copy the code
# Method 2:
@register.inclusion_tag("page.html")
def pagination(num) :
    return {'num': range(1, num + 1)}  Return a dictionary

<nav aria-label="Page navigation">
    <ul class="pagination">
        <li>
            <a href= "#"aria-label="Previous">
                <span aria-hidden="true"> &laquo; </span>
            </a>
        </li>
        {% for page in num %}
            <li><a href= "#" > {{page}} < /a></li>
        {% endfor %}
        <li>
            <a href= "#"aria-label="Next">
                <span aria-hidden="true"> &raquo; </span>
            </a>
        </li>
    </ul>
</nav>
Copy the code