Methods

@classonlymethoddefas_view(cls,**initkwargs):""" Main entry point for a request-response process. """# sanitize keyword argumentsforkeyininitkwargs:ifkeyincls.http_method_names:raiseTypeError(u"You tried to pass in the %s method name as a "u"keyword argument to %s(). Don't do that."%(key,cls.__name__))ifnothasattr(cls,key):raiseTypeError(u"%s() received an invalid keyword %r"%(cls.__name__,key))defview(request,*args,**kwargs):self=cls(**initkwargs)ifhasattr(self,'get')andnothasattr(self,'head'):self.head=self.getreturnself.dispatch(request,*args,**kwargs)# take name and docstring from classupdate_wrapper(view,cls,updated=())# and possible attributes set by decorators# like csrf_exempt from dispatchupdate_wrapper(view,cls.dispatch,assigned=())returnview

defdispatch(self,request,*args,**kwargs):# Try to dispatch to the right method; if a method doesn't exist,# defer to the error handler. Also defer to the error handler if the# request method isn't on the approved list.ifrequest.method.lower()inself.http_method_names:handler=getattr(self,request.method.lower(),self.http_method_not_allowed)else:handler=self.http_method_not_allowedself.request=requestself.args=argsself.kwargs=kwargsreturnhandler(request,*args,**kwargs)

BaseDateListView

Get the context. Must return a Context (or subclass) instance.

220
221
222
223
224
225
226
227

defget_context_data(self,**kwargs):""" Get the context. Must return a Context (or subclass) instance. """items=kwargs.pop('object_list')context=super(BaseDateListView,self).get_context_data(object_list=items)context.update(kwargs)returncontext

MultipleObjectMixin

defget_context_data(self,**kwargs):""" Get the context for this view. """queryset=kwargs.pop('object_list')page_size=self.get_paginate_by(queryset)context_object_name=self.get_context_object_name(queryset)ifpage_size:paginator,page,queryset,is_paginated=self.paginate_queryset(queryset,page_size)context={'paginator':paginator,'page_obj':page,'is_paginated':is_paginated,'object_list':queryset}else:context={'paginator':None,'page_obj':None,'is_paginated':False,'object_list':queryset}context.update(kwargs)ifcontext_object_nameisnotNone:context[context_object_name]=querysetreturncontext

defget_context_object_name(self,object_list):""" Get the name of the item to be used in the context. """ifself.context_object_name:returnself.context_object_nameelifhasattr(object_list,'model'):returnsmart_str('%s_list'%object_list.model._meta.object_name.lower())else:returnNone

Get a queryset properly filtered according to `allow_future` and any
extra lookup kwargs.

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

defget_dated_queryset(self,**lookup):""" Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """qs=self.get_queryset().filter(**lookup)date_field=self.get_date_field()allow_future=self.get_allow_future()allow_empty=self.get_allow_empty()ifnotallow_future:qs=qs.filter(**{'%s__lte'%date_field:timezone.now()})ifnotallow_emptyandnotqs:raiseHttp404(_(u"No %(verbose_name_plural)s available")%{'verbose_name_plural':force_unicode(qs.model._meta.verbose_name_plural)})returnqs

defget_date_field(self):""" Get the name of the date field to be used to filter by. """ifself.date_fieldisNone:raiseImproperlyConfigured(u"%s.date_field is required."%self.__class__.__name__)returnself.date_field

Get a date list by calling `queryset.dates()`, checking along the way
for empty lists that aren't allowed.

204
205
206
207
208
209
210
211
212
213
214
215
216

defget_date_list(self,queryset,date_type):""" Get a date list by calling `queryset.dates()`, checking along the way for empty lists that aren't allowed. """date_field=self.get_date_field()allow_empty=self.get_allow_empty()date_list=queryset.dates(date_field,date_type)[::-1]ifdate_listisnotNoneandnotdate_listandnotallow_empty:name=force_unicode(queryset.model._meta.verbose_name_plural)raiseHttp404(_(u"No %(verbose_name_plural)s available")%{'verbose_name_plural':name})returndate_list

defget_month(self):"Return the month for which this view should display data"month=self.monthifmonthisNone:try:month=self.kwargs['month']exceptKeyError:try:month=self.request.GET['month']exceptKeyError:raiseHttp404(_(u"No month specified"))returnmonth

defget_next_month(self,date):""" Get the next valid month. """first_day,last_day=_month_bounds(date)next=(last_day+datetime.timedelta(days=1)).replace(day=1)return_get_next_prev_month(self,next,is_previous=False,use_first_day=True)

defget_paginator(self,queryset,per_page,orphans=0,allow_empty_first_page=True):""" Return an instance of the paginator for this view. """returnself.paginator_class(queryset,per_page,orphans=orphans,allow_empty_first_page=allow_empty_first_page)

Get the list of items for this view. This must be an interable, and may
be a queryset (in which qs-specific behavior will be enabled).

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

defget_queryset(self):""" Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). """ifself.querysetisnotNone:queryset=self.querysetifhasattr(queryset,'_clone'):queryset=queryset._clone()elifself.modelisnotNone:queryset=self.model._default_manager.all()else:raiseImproperlyConfigured(u"'%s' must define 'queryset' or 'model'"%self.__class__.__name__)returnqueryset

defget_template_names(self):""" Return a list of template names to be used for the request. Must return a list. May not be called if get_template is overridden. """try:names=super(MultipleObjectTemplateResponseMixin,self).get_template_names()exceptImproperlyConfigured:# If template_name isn't specified, it's not a problem --# we just start with an empty list.names=[]# If the list is a queryset, we'll invent a template name based on the# app and model name. This name gets put at the end of the template# name list so that user-supplied names override the automatically-# generated ones.ifhasattr(self.object_list,'model'):opts=self.object_list.model._metanames.append("%s/%s%s.html"%(opts.app_label,opts.object_name.lower(),self.template_name_suffix))returnnames

TemplateResponseMixin

Returns a list of template names to be used for the request. Must return
a list. May not be called if render_to_response is overridden.

100
101
102
103
104
105
106
107
108
109
110

defget_template_names(self):""" Returns a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden. """ifself.template_nameisNone:raiseImproperlyConfigured("TemplateResponseMixin requires either a definition of ""'template_name' or an implementation of 'get_template_names()'")else:return[self.template_name]

defget_year(self):"Return the year for which this view should display data"year=self.yearifyearisNone:try:year=self.kwargs['year']exceptKeyError:try:year=self.request.GET['year']exceptKeyError:raiseHttp404(_(u"No year specified"))returnyear

Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.

19
20
21
22
23
24
25
26
27

def__init__(self,**kwargs):""" Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """# Go through keyword arguments, and either save their values to our# instance, or raise an error.forkey,valueinkwargs.iteritems():setattr(self,key,value)

defpaginate_queryset(self,queryset,page_size):""" Paginate the queryset, if needed. """paginator=self.get_paginator(queryset,page_size,allow_empty_first_page=self.get_allow_empty())page=self.kwargs.get('page')orself.request.GET.get('page')or1try:page_number=int(page)exceptValueError:ifpage=='last':page_number=paginator.num_pageselse:raiseHttp404(_(u"Page is not 'last', nor can it be converted to an int."))try:page=paginator.page(page_number)return(paginator,page,page.object_list,page.has_other_pages())exceptInvalidPage:raiseHttp404(_(u'Invalid page (%(page_number)s)')%{'page_number':page_number})

defrender_to_response(self,context,**response_kwargs):""" Returns a response with a template rendered with the given context. """returnself.response_class(request=self.request,template=self.get_template_names(),context=context,**response_kwargs)