class-based view in Django

Introduction

  • Django 在早先的时候只有function based view。

  • function based view 非常的简答, 很难扩展和自定义。为了解决这些问题,class-based view 出现了。

  • 实际上class-based view也是function,在URL config的时候,我们是有class method view.as_view(), 它就会return a function。

Class-Based View Example

For example, if you created a view extending the django.views.View base class, the dispatch() method will handle the HTTP method logic. If the request is a POST, it will execute the post() method inside the view, if the request is a GET, it will execute the get() method inside the view.

views.py

from django.views import View

class ContactView(View):
    def get(self, request):
        # Code block for GET request

    def post(self, request):
        # Code block for POST request

urls.py

urlpatterns = [
    url(r'contact/$', views.ContactView.as_view(), name='contact'),
]

Function-Based View Example

In function-based views, this logic is handled with if statements:

views.py

def contact(request):
    if request.method == 'POST':
        # Code block for POST request
    else:
        # Code block for GET request (will also match PUT, HEAD, DELETE, etc)

urls.py

urlpatterns = [
    url(r'contact/$', views.contact, name='contact'),
]

References:
https://simpleisbetterthancomplex.com/article/2017/03/21/class-based-views-vs-function-based-views.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容