美文网首页
class-based view in Django

class-based view in Django

作者: Zihowe | 来源:发表于2017-07-28 07:02 被阅读9次

    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

    相关文章

      网友评论

          本文标题:class-based view in Django

          本文链接:https://www.haomeiwen.com/subject/mpqxlxtx.html