ホームページ >バックエンド開発 >Python チュートリアル >Django クラスベースのビューが簡単に

Django クラスベースのビューが簡単に

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2024-10-12 14:13:30508ブラウズ

Django Class Based View made easy

As we all know, django uses MVT (model-view-template) for its design on developing web application.

View itself is a callable which takes a request and returns a response. its more than just a function as Django provides something called Class Based View, so developer can write a view using, well, a class based approach or you can say an OOP approach. This Class Based View is designed so we can structure our views and can be reused by the power of inheritance and mixins.

As documented well in django docs, one of the problem with function based view is that there is no way to extend or customize them beyond some configuration options, limiting their usefulness in many real-world applications.

The toolkit of base classes and mixins in django is designed for maximum flexibility. Lets take a look how we can use most basic Class Based View in django using View class inheritance and compare it to function based view.

#views.py using View class inheritance
from django.views import View
from django.http import HttpResponse, HttpRequest

class IndexView(View):
    def get(self, request: HttpRequest):
        # imagine 10 line of view logic here
        return HttpResponse("Hello world from indexview")

    def post(self, request: HttpRequest):
        # imagine 10 line of view logic here
        return HttpResponse("Hello world from indexview in post method")

#views.py function based view
from django.http import HttpResponse, HttpRequest

def index(request: HttpRequest):
    if request.method == "GET":
        # imagine 10 line of view logic here
        return HttpResponse("Hello world from index funcion view")
    elif request.method == "POST":
        # imagine 10 line of view logic here
        return HttpResponse("Hello world from index funcion view in post method")

If you look at above, a class-based view allows you to respond to different HTTP request methods with different class instance methods, instead of with conditionally branching code inside a single view function. now imagine in each view above that we added 10 lines of logic each method, you should be can tell which one is easier to walkthrough.

In order to register the class based view into the url configuration is that we must call as_view() class method which will basically convert the Class View into a callable function. this converted function will call setup() to initialize its attribute and then calls dispatch() to check which method user have (a GET, POST, or other method) and will connect the request method to coressponding matching method the class based view originally have

#urls.py

from django.urls import path
from myapp.views import IndexView, index

urlpatterns = [
    path("", IndexView.as_view(), name=IndexView.__name__), 
    path("index/", index, name=index.__name__),

]

class based view also supports all http shourtcut django has, such as render() function to render a template, here is a modified example of django cbv using render shortcut and cooperated with django messages framework

class IndexView(View):
    def get(self, request: HttpRequest):
        # imagine 10 line of view logic here
        return render(request, "GEtindex.html")

    def post(self, request: HttpRequest):
        # imagine 10 line of view logic here
        messages.add_message(request, messages.INFO, "POST Success") #add display success message here by django messages framework
        return render(request, "POSTindex.html")

Overall django class based view allow developer to write better to understand view logic, the more complex a view logic is, Im pretty sure it will be harder to read if we just use function based view (too many if statement to check what method are user using for an example) and hard to scale, meanwhile django cbv is designed to break our view logic to multiple method like get and post method. and can be used again in inheritance if you want, altho i can argue that the more inheritance we have in a class it will be harder to read due to its abstraction.

you can check more about class based view in django docs starts from here, here, here

Also a good alternative docs that focuses in django class based view is ccbv.co.uk <- i use this website to know which view template logic i can use fast!

以上がDjango クラスベースのビューが簡単にの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:ダブルルーン次の記事:ダブルルーン