@classonlymethoddefas_view(cls,**initkwargs):""" Main entry point for a request-response process. """# sanitize keyword argumentsforkeyininitkwargs:ifkeyincls.http_method_names:raiseTypeError("You tried to pass in the %s method name as a ""keyword argument to %s(). Don't do that."%(key,cls.__name__))ifnothasattr(cls,key):raiseTypeError("%s() received an invalid keyword %r. as_view ""only accepts arguments that are already ""attributes of the class."%(cls.__name__,key))defview(request,*args,**kwargs):self=cls(**initkwargs)ifhasattr(self,'get')andnothasattr(self,'head'):self.head=self.getself.request=requestself.args=argsself.kwargs=kwargsreturnself.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_allowedreturnhandler(request,*args,**kwargs)

SingleObjectMixin

Insert the single object into the context dict.

91
92
93
94
95
96
97
98
99
100

defget_context_data(self,**kwargs):""" Insert the single object into the context dict. """context={}context_object_name=self.get_context_object_name(self.object)ifcontext_object_name:context[context_object_name]=self.objectcontext.update(kwargs)returnsuper(SingleObjectMixin,self).get_context_data(**context)

defget_context_object_name(self,obj):""" Get the name to use for the object. """ifself.context_object_name:returnself.context_object_nameelifisinstance(obj,models.Model):returnobj._meta.object_name.lower()else:returnNone

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

defget_day(self):""" Return the day for which this view should display data. """day=self.dayifdayisNone:try:day=self.kwargs['day']exceptKeyError:try:day=self.request.GET['day']exceptKeyError:raiseHttp404(_("No day specified"))returnday

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(_("No month specified"))returnmonth

Return the start date of the next interval.
The interval is defined by start date <= item date < next start date.

113
114
115
116
117
118
119
120
121

def_get_next_month(self,date):""" Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ifdate.month==12:returndate.replace(year=date.year+1,month=1,day=1)else:returndate.replace(month=date.month+1,day=1)

BaseDateDetailView

defget_object(self,queryset=None):""" Get the object this request displays. """year=self.get_year()month=self.get_month()day=self.get_day()date=_date_from_string(year,self.get_year_format(),month,self.get_month_format(),day,self.get_day_format())# Use a custom queryset if providedqs=querysetorself.get_queryset()ifnotself.get_allow_future()anddate>datetime.date.today():raiseHttp404(_("Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.")%{'verbose_name_plural':qs.model._meta.verbose_name_plural,'class_name':self.__class__.__name__,})# Filter down a queryset from self.queryset using the date from the# URL. This'll get passed as the queryset to DetailView.get_object,# which'll handle the 404lookup_kwargs=self._make_single_date_lookup(date)qs=qs.filter(**lookup_kwargs)returnsuper(BaseDetailView,self).get_object(queryset=qs)

SingleObjectMixin

Returns the object the view is displaying.
By default this requires `self.queryset` and a `pk` or `slug` argument
in the URLconf, but subclasses can override this to return any object.

defget_object(self,queryset=None):""" Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """# Use a custom queryset if provided; this is required for subclasses# like DateDetailViewifquerysetisNone:queryset=self.get_queryset()# Next, try looking up by primary key.pk=self.kwargs.get(self.pk_url_kwarg,None)slug=self.kwargs.get(self.slug_url_kwarg,None)ifpkisnotNone:queryset=queryset.filter(pk=pk)# Next, try looking up by slug.elifslugisnotNone:slug_field=self.get_slug_field()queryset=queryset.filter(**{slug_field:slug})# If none of those are defined, it's an error.else:raiseAttributeError("Generic detail view %s must be called with ""either an object pk or a slug."%self.__class__.__name__)try:# Get the single item from the filtered querysetobj=queryset.get()exceptObjectDoesNotExist:raiseHttp404(_("No %(verbose_name)s found matching the query")%{'verbose_name':queryset.model._meta.verbose_name})returnobj

Get the queryset to look an object up against. May not be called if
`get_object` is overridden.

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

defget_queryset(self):""" Get the queryset to look an object up against. May not be called if `get_object` is overridden. """ifself.querysetisNone:ifself.model:returnself.model._default_manager.all()else:raiseImproperlyConfigured("%(cls)s is missing a queryset. Define ""%(cls)s.model, %(cls)s.queryset, or override ""%(cls)s.get_queryset()."%{'cls':self.__class__.__name__})returnself.queryset._clone()

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(_("No year specified"))returnyear

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

35
36
37
38
39
40
41
42
43

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,valueinsix.iteritems(kwargs):setattr(self,key,value)

Convert a date into a datetime when the date field is a DateTimeField.
When time zone support is enabled, `date` is assumed to be in the
current time zone, so that displayed items are consistent with the URL.

292
293
294
295
296
297
298
299
300
301
302

def_make_date_lookup_arg(self,value):""" Convert a date into a datetime when the date field is a DateTimeField. When time zone support is enabled, `date` is assumed to be in the current time zone, so that displayed items are consistent with the URL. """ifself.uses_datetime_field:value=datetime.datetime.combine(value,datetime.time.min)ifsettings.USE_TZ:value=timezone.make_aware(value,timezone.get_current_timezone())returnvalue

Get the lookup kwargs for filtering on a single date.
If the date field is a DateTimeField, we can't just filter on
date_field=date because that doesn't take the time into account.

305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321

def_make_single_date_lookup(self,date):""" Get the lookup kwargs for filtering on a single date. If the date field is a DateTimeField, we can't just filter on date_field=date because that doesn't take the time into account. """date_field=self.get_date_field()ifself.uses_datetime_field:since=self._make_date_lookup_arg(date)until=self._make_date_lookup_arg(date+datetime.timedelta(days=1))return{'%s__gte'%date_field:since,'%s__lt'%date_field:until,}else:# Skip self._make_date_lookup_arg, it's a no-op in this branch.return{date_field:date}