Django class-based view

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 HttpResponse
from django.views.generic import View

class MyView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

Example urls.py:

from django.conf.urls import patterns, url

from myapp.views import MyView

urlpatterns = 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 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.base 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 GETPOST, 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 patterns
from myapp.views import MyView

urlpatterns = 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 HttpResponse
from django.views.generic.base import View

class 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:

Method Flowchart

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

Example views.py:

from django.views.generic.base import TemplateView

from articles.models import Article

class 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, url

from myapp.views import HomePageView

urlpatterns = 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.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值