Django class-based view

来源:互联网 发布:java实战案例 编辑:程序博客网 时间:2024/05/13 09:07

View

class django.views.generic.base.View

The master class-based base view. All other class-based views inherit from this base class.

Method Flowchart

  1. dispatch()
  2. http_method_not_allowed()
  3. options()

Example views.py:

from django.http import HttpResponsefrom django.views.generic import Viewclass MyView(View):    def get(self, request, *args, **kwargs):        return HttpResponse('Hello, World!')

Example urls.py:

from django.conf.urls import patterns, urlfrom myapp.views import MyViewurlpatterns = patterns('',    url(r'^mine/$', MyView.as_view(), name='my-view'),)

Attributes

http_method_names

The list of HTTP method names that this view will accept.

Default:

['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']

Methods

classmethod as_view(**initkwargs)

Returns a callable view that takes a request and returns a response:

response = MyView.as_view()(request)

----------------------------------------------------------------------------------------------------------------------------------------------

Using class-based views

At its core, 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 HttpResponsedef my_view(request):    if request.method == 'GET':        # <view logic>        return HttpResponse('result')

In a class-based view, this would become:

from django.http import HttpResponsefrom django.views.generic.base import Viewclass 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 GETPOST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed if not:

# urls.pyfrom django.conf.urls import patternsfrom myapp.views import MyViewurlpatterns = patterns('',    (r'^about/', MyView.as_view()),)

It is worth noting that what your method returns is identical to what you return from a function-based view, namely some form of HttpResponse. This means that http shortcuts or TemplateResponse objects are valid to use inside a class-based view.

While a minimal class-based view does not require any class attributes to perform its job, class attributes are useful in many class-based designs, and there are two ways to configure or set class attributes.

The first is the standard Python way of subclassing and overriding attributes and methods in the subclass. So that if your parent class had an attribute greeting like this:

from django.http import HttpResponsefrom django.views.generic.base import Viewclass GreetingView(View):    greeting = "Good Day"    def get(self, request):        return HttpResponse(self.greeting)

You can override that in a subclass:

class MorningGreetingView(GreetingView):    greeting = "Morning to ya"

Another option is to configure class attributes as keyword arguments to the as_view() call in the URLconf:

urlpatterns = patterns('',    (r'^about/', GreetingView.as_view(greeting="G'day")),)
--------------------------------------------------------------------------------------------------------------------------------------------

TemplateView

class django.views.generic.base.TemplateView

Renders a given template, with the context containing parameters captured in the URL.

Ancestors (MRO)

This view inherits methods and attributes from the following views:

  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.base.View

Method Flowchart

  1. dispatch()
  2. http_method_not_allowed()
  3. get_context_data()

Example views.py:

from django.views.generic.base import TemplateViewfrom articles.models import Articleclass HomePageView(TemplateView):    template_name = "home.html"    def get_context_data(self, **kwargs):        context = super(HomePageView, self).get_context_data(**kwargs)        context['latest_articles'] = Article.objects.all()[:5]        return context

Example urls.py:

from django.conf.urls import patterns, urlfrom myapp.views import HomePageViewurlpatterns = patterns('',    url(r'^$', HomePageView.as_view(), name='home'),)

Context

  • params: The dictionary of keyword arguments captured from the URL pattern that served the view.

get_context_data(**kwargs)

Returns a dictionary representing the template context. The keyword arguments provided will make up the returned context. Example usage:

def get_context_data(self, **kwargs):    context = super(RandomNumberView, self).get_context_data(**kwargs)    context['number'] = random.randrange(1, 100)    return context

The template context of all class-based generic views include a view variable that points to the View instance.