2015年1月29日木曜日

Using class-based views

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.
So where the code to handle HTTP GET in a view function would look something like:
from django.http import HttpResponse
def my_view(request):
if request.method == 'GET':
# <view logic>
return HttpResponse('result')
In a class-based view, this would become:
from django.http import HttpResponse
from django.views.generic import View
class MyView(View):
def get(self, request):
# <view logic>
return HttpResponse('result')
Because Django's URL resolver expects to send the request and associated arguments to a callable function, not a
class, class-based views have an as_view() class method which serves as the callable entry point to your class. The
as_view entry point creates an instance of your class and calls its dispatch() method. dispatch looks at the
request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or
raises HttpResponseNotAllowed if not:
# urls.py
from django.conf.urls import url
from myapp.views import MyView
urlpatterns = [
url(r'^about/', MyView.as_view()),
]

0 件のコメント:

コメントを投稿