Django class-based view
2013-10-26 15:05
435 查看
View
class django.views.generic.base.ViewThe 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 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'), )
Attributeshttp_method_namesThe list of HTTP method names that this view will accept.Default:['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']Methodsclassmethod as_view(**initkwargs)Returns a callable view that takes a request and returns a response:
response = MyView.as_view()(request)
In a class-based view, this would become:----------------------------------------------------------------------------------------------------------------------------------------------
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')
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 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 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")),)
--------------------------------------------------------------------------------------------------------------------------------------------
Example urls.py:TemplateView
class django.views.generic.base.TemplateViewRenders 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 Flowchartdispatch() http_method_not_allowed() 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
from django.conf.urls import patterns, url from myapp.views import HomePageView urlpatterns = patterns('', url(r'^$', HomePageView.as_view(), name='home'), )Contextparams: 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 contextThe template context of all class-based generic views include a view variable that points to the View instance.
相关文章推荐
- Django学习小记[6]——Class-based View
- Django——基于类的视图(class-based view)
- django Class-based View
- Django class-based view的QuerySet三个层次以及函数调用路线图
- Django class-based views
- django为Form生成的label标签添加class
- Django+jenkins+python+RESTful framework(基于Class的视图)(4) 转发邮件
- 基于 Django1.10 文档的深入学习(4)—— models.py 之 class Meta
- django rest framework 入门3——Class Based Views
- 方法实现django class-based views介绍与分析
- Django学习笔记之Class-Based-View
- 从django的注册机制探究class-based views
- django 运行报错:某个class 没有 objects 属性问题?及解决方案。
- Django restframwork教程之类视图(class-based views)
- 深入学习Django源码基础1 - 深刻理解Python中的元类(metaclass)
- Django Restful API Class Based View
- 关于DjangoRuntimeError: Model class doesn't declare an explicit app_label
- Django Class-based generic views 基于类的通用视图
- 基于 Django1.10 文档的深入学习(32)—— Introduction to class-based views
- Django Form源码分析之Metaclass的应用