3.1 視圖基礎
任何可以調用的python都可以作為視圖。
3.2 generic & class based views
通用以及基于類的視圖
provide higher levels of abstraction and composability
also hide a lot of complexity, which can be confusing for the newcomer
luckily the documentation is much better with django 1.5
django 1.3 introduced class based views, which is what we’ll be focusing on here. class based views, or cbvs, can
eliminate a lot of boilerplate from your views, especially for things like an edit view where you want to take different
action on a get vs post. they give you a lot of power to compose functionality from pieces. the downside is that
this power comes with some added complexity.
3.3 class based views
基于類的視圖
the minimal class based view subclasses view (https://docs.djangoproject.com/en/1.5/ref/class-based-
views/base/#view) and implements methods for the http methods it supports. here’s the class-based version
of the minimalist “hello, world” view we previously wrote.
from django.http import httpresponse
from django.views.generic import view
class myview(view):
def get(self, request, *args, **kwargs):
return httpresponse("hello, world")
in a class based view, http methods map to class method names. in this case, we’ve defined a handler for get
requests with the get method. just like the function implementation, it takes request as its first argument, and
returns an http response.
permissive signatures
you may notice that it has a couple of extra arguments in its signature, compared to the view we saw previ-
ously, specifically *args and **kwargs. class based views were first introduced as a way to make django’s
“generic” views more flexible. that meant they were used in many different contexts, with potentially different
arguments extracted from the urls. as i’ve been writing class based views over the past year, i’ve continued to
write them with permissive signatures, as i’ve found they’re often useful in ways i didn’t initially expect.