Introduction
Django 在早先的時(shí)候只有function based view简烘。
function based view 非常的簡答, 很難擴(kuò)展和自定義定枷。為了解決這些問題孤澎,class-based view 出現(xiàn)了。
實(shí)際上class-based view也是function欠窒,在URL config的時(shí)候覆旭,我們是有class method view.as_view(), 它就會(huì)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