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
- dispatch()
- http_method_not_allowed()
- 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 GET, POST, 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
- dispatch()
- http_method_not_allowed()
- 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.
- Django class-based view
- django class-based view
- Django class based view walkthrough: TemplateView
- Django 学习笔记之 Class-Based-View
- Django学习小记[6]——Class-based View
- Django class-based views
- class based generic view
- Django class-based view的QuerySet三个层次以及函数调用路线图
- restframework之Class-View-Based
- django class-based views介绍与分析
- python django rest framework Class-based Views
- [Django] View class and Form
- django rest framework 入门3——Class Based Views
- Django-Rest-Framework 教程: 3. 使用 class based views
- django-rest-framework指南(3):Class Based Views(类视图)
- Django REST framework-教程03-class-based views原创翻译
- 深度解读django class base view 之 detaiview
- Django 1.6 最佳实践: 如何正确使用 CBVs (Class-based views)
- libgdx中关于Sprite透明度无效的一深坑
- 单链表是否相交,是否存在环
- Linux 文件系统 之 文件描述符与读写指针
- 计算机视觉处理的国际顶级会议
- 遍历一文件夹的所有文件/文件夹
- Django class-based view
- 国企,私企与外企利弊通观
- 添加标题栏 CMFCCaptionBar
- 定义一个点Point,并定义成员函数double Distance(const& Point),求两点的距离。
- 桶中取黑白球(编程之美)
- vm对死亡的定义
- linuxzImage生成过程详解
- jsp实例及乱码问题
- iOS学习资源01——Github上的600多个iOS开源类库