您的位置:首页 > 编程语言 > Go语言

Django class-based view

2013-10-26 15:05 435 查看


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 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)


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

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 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")),)
--------------------------------------------------------------------------------------------------------------------------------------------

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
Example urls.py:
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 context
The template context of all class-based generic views include a view variable that points to the View instance.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: