@classonlymethoddefas_view(cls,**initkwargs):"""Main entry point for a request-response process."""forkeyininitkwargs: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.setup(request,*args,**kwargs)ifnothasattr(self,'request'):raiseAttributeError("%s instance has no 'request' attribute. Did you override ""setup() and forget to call super()?"%cls.__name__)returnself.dispatch(request,*args,**kwargs)view.view_class=clsview.view_initkwargs=initkwargs# 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
89
90
91
92
93
94
95
96
97
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)
Return `True` if the view should be allowed to display objects from
the future.
240
241
242
243
244
245
defget_allow_future(self):""" Return `True` if the view should be allowed to display objects from the future. """returnself.allow_future
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={}ifself.object:context['object']=self.objectcontext_object_name=self.get_context_object_name(self.object)ifcontext_object_name:context[context_object_name]=self.objectcontext.update(kwargs)returnsuper().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.model_nameelse:returnNone
Get the name of the date field to be used to filter by.
234
235
236
237
238
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
Return the day for which this view should display data.
132
133
134
135
136
137
138
139
140
141
142
143
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
Get a day format string in strptime syntax to be used to parse the day
from url variables.
125
126
127
128
129
130
defget_day_format(self):""" Get a day format string in strptime syntax to be used to parse the day from url variables. """returnself.day_format
Return the month for which this view should display data.
80
81
82
83
84
85
86
87
88
89
90
91
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
Get a month format string in strptime syntax to be used to parse the
month from url variables.
73
74
75
76
77
78
defget_month_format(self):""" Get a month format string in strptime syntax to be used to parse the month from url variables. """returnself.month_format
Get the next valid day.
145
146
147
defget_next_day(self,date):"""Get the next valid day."""return_get_next_prev(self,date,is_previous=False,period='day')
Get the next valid month.
93
94
95
defget_next_month(self,date):"""Get the next valid month."""return_get_next_prev(self,date,is_previous=False,period='month')
Get the next valid year.
44
45
46
defget_next_year(self,date):"""Get the next valid year."""return_get_next_prev(self,date,is_previous=False,period='year')
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=self.get_queryset()ifquerysetisNoneelsequerysetifnotself.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().get_object(queryset=qs)
SingleObjectMixin
Return the object the view is displaying.
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
Subclasses can override this to return any object.
defget_object(self,queryset=None):""" Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. 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)slug=self.kwargs.get(self.slug_url_kwarg)ifpkisnotNone:queryset=queryset.filter(pk=pk)# Next, try looking up by slug.ifslugisnotNoneand(pkisNoneorself.query_pk_and_slug):slug_field=self.get_slug_field()queryset=queryset.filter(**{slug_field:slug})# If none of those are defined, it's an error.ifpkisNoneandslugisNone:raiseAttributeError("Generic detail view %s must be called with either an object ""pk or a slug in the URLconf."%self.__class__.__name__)try:# Get the single item from the filtered querysetobj=queryset.get()exceptqueryset.model.DoesNotExist:raiseHttp404(_("No %(verbose_name)s found matching the query")%{'verbose_name':queryset.model._meta.verbose_name})returnobj
Get the previous valid day.
149
150
151
defget_previous_day(self,date):"""Get the previous valid day."""return_get_next_prev(self,date,is_previous=True,period='day')
Get the previous valid month.
97
98
99
defget_previous_month(self,date):"""Get the previous valid month."""return_get_next_prev(self,date,is_previous=True,period='month')
Get the previous valid year.
48
49
50
defget_previous_year(self,date):"""Get the previous valid year."""return_get_next_prev(self,date,is_previous=True,period='year')
Return the `QuerySet` that will be used to look up the object.
This method is called by the default implementation of get_object() and
may not be called if get_object() is overridden.
defget_queryset(self):""" Return the `QuerySet` that will be used to look up the object. This method is called by the default implementation of get_object() and 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.all()
Get the name of a slug field to be used to look up by slug.
78
79
80
defget_slug_field(self):"""Get the name of a slug field to be used to look up by slug."""returnself.slug_field
Возвращает год, для которого это представление должно отображать данные.
31
32
33
34
35
36
37
38
39
40
41
42
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
Получает строку в формате года в синтаксисе strptime, которая будет использоваться для анализа года по переменным URL.
24
25
26
27
28
29
defget_year_format(self):""" Get a year format string in strptime syntax to be used to parse the year from url variables. """returnself.year_format
99
100
101
102
103
104
defhttp_method_not_allowed(self,request,*args,**kwargs):logger.warning('Method Not Allowed (%s): %s',request.method,request.path,extra={'status_code':405,'request':request})returnHttpResponseNotAllowed(self._allowed_methods())
Обрабатывает ответы на запросы для запроса HTTP OPTIONS.
106
107
108
109
110
111
defoptions(self,request,*args,**kwargs):"""Handle responding to requests for the OPTIONS HTTP verb."""response=HttpResponse()response['Allow']=', '.join(self._allowed_methods())response['Content-Length']='0'returnresponse
Initialize attributes shared by all view methods.
83
84
85
86
87
defsetup(self,request,*args,**kwargs):"""Initialize attributes shared by all view methods."""self.request=requestself.args=argsself.kwargs=kwargs
def_get_current_day(self,date):"""Return the start date of the current interval."""returndate
Возвращает дату начала текущего интервала.
115
116
117
def_get_current_month(self,date):"""Return the start date of the previous interval."""returndate.replace(day=1)
Возвращает дату начала текущего интервала.
63
64
65
def_get_current_year(self,date):"""Return the start date of the current interval."""returndate.replace(month=1,day=1)
Возвращает дату начала следующего интервала.
Интервал определяется датой начала <= дата элемента < следующая дата начала.
153
154
155
156
157
158
def_get_next_day(self,date):""" Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """returndate+datetime.timedelta(days=1)
Возвращает дату начала следующего интервала.
Интервал определяется датой начала <= дата элемента < следующая дата начала.
101
102
103
104
105
106
107
108
109
110
111
112
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:try:returndate.replace(year=date.year+1,month=1,day=1)exceptValueError:raiseHttp404(_("Date out of range"))else:returndate.replace(month=date.month+1,day=1)
Возвращает дату начала следующего интервала.
Интервал определяется датой начала <= дата элемента < следующая дата начала.
52
53
54
55
56
57
58
59
60
def_get_next_year(self,date):""" Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """try:returndate.replace(year=date.year+1,month=1,day=1)exceptValueError:raiseHttp404(_("Date out of range"))
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.
260
261
262
263
264
265
266
267
268
269
270
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)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.
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}
Конструктор. Вызывается в URLconf; может содержать полезные дополнительные ключевые аргументы и другие вещи.
38
39
40
41
42
43
44
45
46
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.items():setattr(self,key,value)