Fbv and CBV in Django

Source: Internet
Author: User

In Django, two request processing methods are available: fbv and CBV.

 

I. fbv

Fbv (function base views)Is to use functions in the view to process requests.

Check the Code:

URLs. py

12345678 from django.conf.urls import url, include# from django.contrib import adminfrom mytest import views urlpatterns = [    # url(r‘^admin/‘, admin.site.urls),    url(r‘^index/‘, views.index),]

Views. py

123456789 from django.shortcuts import renderdef index(req):    if req.method == ‘POST‘:        print(‘method is :‘ + req.method)    elif req.method == ‘GET‘:        print(‘method is :‘ + req.method)    return render(req, ‘index.html‘)

Note that the function [DEF index (req):] is defined here ):]

Index.html

12345678910111213 <!DOCTYPE html>="en">    <meta charset="UTF-8">    <title>index</title></head><body>    <form action="" method="post">        <input type="text" name="A" />        <input type="submit" name="b" value="Submit" />    </form></body></html>

The above is the use of fbv.

Ii. CBV

CBV (class base views)The class is used to process requests in the view.

Modify URLs. py in the above Code as follows:

123456 from mytest import views urlpatterns = [    # url(r‘^index/‘, views.index),    url(r‘^index/‘, views.Index.as_view()),]

Note: URL (R' ^ index/', views. Index. as_view () is a fixed usage.

Modify views. py in the above Code as follows:

1234567891011 from django.views import Viewclass Index(View):    def get(self, req):        print(‘method is :‘ + req.method)        return render(req, ‘index.html‘)     def post(self, req):        print(‘method is :‘ + req.method)        return render(req, ‘index.html‘)

Note: To Inherit the view, the number of letters in the class must be in lower case.

 

You can use either of the two methods.

Fbv and CBV in Django

Fbv and CBV in Django

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.