(Django) 11 class views

Source: Internet
Author: User

Directory

  • 1. Use Class View
    • Create Class View
    • Register a route
  • Class View with decorator
    • Decoration in URL
    • Decoration in Class View
    • Name parameter of method_decorator
  • Extension class using Mixin

A function-defined view is called a function view, which is easy to use and easy to understand. However, when a s view has multiple request methods, you need to use the branch to compile the logic corresponding to different request methods.

Using the function view, the code looks like this

def my_view(request):    if request.method == ‘GET‘:        return HttpResponse("get")    if request.method == ‘POST‘:        return HttpResponse("post")
1. Use Class View

The core of the class-based view is to allow you to use different instance methods to respond to different HTTP request methods, rather than using conditional branch code in a view function.

Create Class View

Use the Class View, the code is like this

from django.views import Viewclass ClassView(View):    def get(self, request):        return HttpResponse("get")    def post(self, request):        return HttpResponse("post")

The Class View must inheritViewClass, usefrom django.views import ViewImport

Register a route

When configuring the Class Viewas_viewMethod registration route

urlpatterns = [    url(r‘^class_view‘, views.ClassView.as_view(), name="class_view")]

as_viewWill return a reference to a method in the class, it willView, RundispatchMethod,dispatchThe method will find class methods like get \ post in the class, and then match with the request method. After matching, the reference of this method will be returned.

If you sendGETRequest, he willGETConvert to lowercase and match with the method in the class, and then matchgetMethodgetMethod reference is returnedas_viewCall. ThereforegetLast requestedas_viewYesgetMethod reference.

Class View with decorator

You can use the decorator to add functions to the Class View. There are three ways to use the decorator.

  • Decoration in URL Configuration
  • Decoration in Class View
  • Extension class using Mixin

For ease of understanding, use the following cases for demonstration

Def decorator (func): def wrapper (request, * ARGs, ** kwargs): Print ('modifier called ') return func (request, * ARGs, ** kwargs) return wrapperclass classview (View): def get (self, request): Return httpresponse ("get") def post (self, request): Return httpresponse ("Post ")
Decoration in URL
url(r‘^class_view‘, views.decorator(views.ClassView.as_view()), name="class_view")

SendGETOrPOSTType request print result

The decorator is called.

Call this function in the URL andas_viewThe method is passed in. This method will decorate all the requested functions.

This method places the decoration in the URL configuration, which is not conducive to the integrity and readability of the code, so it is generally not used.

Decoration in Class View

In the Class View, decorator cannot be used for decoration.method_decoratorIt applies to the class decorator.

In the decorator we write, the parameter received by the inner function isrequest

Def decorator (func): def wrapper (request, * ARGs, ** kwargs): Print ('modifier called ') return func (request, * ARGs, ** kwargs) return wrapper

In the class view method, the first parameter isself, So usemethod_decoratorAdd the first parameter of the decoratorselfTo use methods in the Class View.

You can also manually add parameters for the decorator.self

Def decorator (func): def wrapper (self, request, * ARGs, ** kwargs): Print ('modifier called ') return func (self, request, * ARGs, ** kwargs) return wrapper
Decoration all methods

Which can be rewritten and decorateddispatchThe Code is as follows:

class ClassView(View):    @method_decorator(decorator)    def dispatch(self, request, *args, **kwargs):        return super().dispatch(request, *args, **kwargs)    def get(self, request):        return HttpResponse("get")    def post(self, request):        return HttpResponse("post")

UseGETOrPOSTRequest Method, the decorator will be executed to print the result

The decorator is called.
Describe only one method
class ClassView(View):    @method_decorator(decorator)    def get(self, request):        return HttpResponse("get")    def post(self, request):        return HttpResponse("post")

Only useGETMethod Request to execute the decorator and print the result

The decorator is called.

POSTMethod.

Name parameter of method_decorator

Decoration Methods

@method_decorator(decorator, name="dispatch")class ClassView(View):    def get(self, request):        return HttpResponse("get")    def post(self, request):        return HttpResponse("post")

Specifies the method to be decorated

@method_decorator(decorator, name="get")class ClassView(View):    def get(self, request):        return HttpResponse("get")    def post(self, request):        return HttpResponse("post")
Extension class using Mixin

The extension class uses Python multi-inheritedMROFeatures.

class MyMixin(object):    @classmethod    def as_view(cls, *args, **kwargs):        view = super().as_view(*args, **kwargs)        view = decorator(view)        return viewclass ClassView(MyMixin, View):    def get(self, request):        return HttpResponse("get")    def post(self, request):        return HttpResponse("post")

This method will decorate all methods. You can use this method to add multiple decorators for the method.

(Django) 11 class views

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.