desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Get a week format string in strptime syntax to be used to parse the
week from url variables.'
| def get_week_format(self):
| return self.week_format
|
'Return the week for which this view should display data'
| def get_week(self):
| week = self.week
if (week is None):
try:
week = self.kwargs[u'week']
except KeyError:
try:
week = self.request.GET[u'week']
except KeyError:
raise Http404(_(u'No week specified'))
return week
|
'Get the next valid week.'
| def get_next_week(self, date):
| return _get_next_prev(self, date, is_previous=False, period=u'week')
|
'Get the previous valid week.'
| def get_previous_week(self, date):
| return _get_next_prev(self, date, is_previous=True, period=u'week')
|
'Return the start date of the next interval.
The interval is defined by start date <= item date < next start date.'
| def _get_next_week(self, date):
| return (date + datetime.timedelta(days=(7 - self._get_weekday(date))))
|
'Return the start date of the current interval.'
| def _get_current_week(self, date):
| return (date - datetime.timedelta(self._get_weekday(date)))
|
'Return the weekday for a given date.
The first day according to the week format is 0 and the last day is 6.'
| def _get_weekday(self, date):
| week_format = self.get_week_format()
if (week_format == u'%W'):
return date.weekday()
elif (week_format == u'%U'):
return ((date.weekday() + 1) % 7)
else:
raise ValueError((u'unknown week format: %s' % week_format))
|
'Get the name of the date field to be used to filter by.'
| def get_date_field(self):
| if (self.date_field is None):
raise ImproperlyConfigured((u'%s.date_field is required.' % self.__class__.__name__))
return self.date_field
|
'Returns `True` if the view should be allowed to display objects from
the future.'
| def get_allow_future(self):
| return self.allow_future
|
'Return `True` if the date field is a `DateTimeField` and `False`
if it\'s a `DateField`.'
| @cached_property
def uses_datetime_field(self):
| model = (self.get_queryset().model if (self.model is None) else self.model)
field = model._meta.get_field(self.get_date_field())
return isinstance(field, models.DateTimeField)
|
'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.'
| def _make_date_lookup_arg(self, value):
| if self.uses_datetime_field:
value = datetime.datetime.combine(value, datetime.time.min)
if settings.USE_TZ:
value = timezone.make_aware(value, timezone.get_current_timezone())
return value
|
'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):
| date_field = self.get_date_field()
if self.uses_datetime_field:
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg((date + datetime.timedelta(days=1)))
return {(u'%s__gte' % date_field): since, (u'%s__lt' % date_field): until}
else:
return {date_field: date}
|
'Obtain the list of dates and items.'
| def get_dated_items(self):
| raise NotImplementedError(u'A DateView must provide an implementation of get_dated_items()')
|
'Get a queryset properly filtered according to `allow_future` and any
extra lookup kwargs.'
| def get_dated_queryset(self, ordering=None, **lookup):
| qs = self.get_queryset().filter(**lookup)
date_field = self.get_date_field()
allow_future = self.get_allow_future()
allow_empty = self.get_allow_empty()
paginate_by = self.get_paginate_by(qs)
if (ordering is not None):
qs = qs.order_by(ordering)
if (not allow_future):
now = (timezone.now() if self.uses_datetime_field else timezone_today())
qs = qs.filter(**{(u'%s__lte' % date_field): now})
if (not allow_empty):
is_empty = ((len(qs) == 0) if (paginate_by is None) else (not qs.exists()))
if is_empty:
raise Http404((_(u'No %(verbose_name_plural)s available') % {u'verbose_name_plural': force_text(qs.model._meta.verbose_name_plural)}))
return qs
|
'Get the aggregation period for the list of dates: \'year\', \'month\', or \'day\'.'
| def get_date_list_period(self):
| return self.date_list_period
|
'Get a date list by calling `queryset.dates()`, checking along the way
for empty lists that aren\'t allowed.'
| def get_date_list(self, queryset, date_type=None, ordering=u'ASC'):
| date_field = self.get_date_field()
allow_empty = self.get_allow_empty()
if (date_type is None):
date_type = self.get_date_list_period()
date_list = queryset.dates(date_field, date_type, ordering)
if ((date_list is not None) and (not date_list) and (not allow_empty)):
name = force_text(queryset.model._meta.verbose_name_plural)
raise Http404((_(u'No %(verbose_name_plural)s available') % {u'verbose_name_plural': name}))
return date_list
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| qs = self.get_dated_queryset(ordering=(u'-%s' % self.get_date_field()))
date_list = self.get_date_list(qs, ordering=u'DESC')
if (not date_list):
qs = qs.none()
return (date_list, qs, {})
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| year = self.get_year()
date_field = self.get_date_field()
date = _date_from_string(year, self.get_year_format())
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(self._get_next_year(date))
lookup_kwargs = {(u'%s__gte' % date_field): since, (u'%s__lt' % date_field): until}
qs = self.get_dated_queryset(ordering=(u'-%s' % date_field), **lookup_kwargs)
date_list = self.get_date_list(qs)
if (not self.get_make_object_list()):
qs = qs.none()
return (date_list, qs, {u'year': date, u'next_year': self.get_next_year(date), u'previous_year': self.get_previous_year(date)})
|
'Return `True` if this view should contain the full list of objects in
the given year.'
| def get_make_object_list(self):
| return self.make_object_list
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| year = self.get_year()
month = self.get_month()
date_field = self.get_date_field()
date = _date_from_string(year, self.get_year_format(), month, self.get_month_format())
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(self._get_next_month(date))
lookup_kwargs = {(u'%s__gte' % date_field): since, (u'%s__lt' % date_field): until}
qs = self.get_dated_queryset(**lookup_kwargs)
date_list = self.get_date_list(qs)
return (date_list, qs, {u'month': date, u'next_month': self.get_next_month(date), u'previous_month': self.get_previous_month(date)})
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| year = self.get_year()
week = self.get_week()
date_field = self.get_date_field()
week_format = self.get_week_format()
week_start = {u'%W': u'1', u'%U': u'0'}[week_format]
date = _date_from_string(year, self.get_year_format(), week_start, u'%w', week, week_format)
since = self._make_date_lookup_arg(date)
until = self._make_date_lookup_arg(self._get_next_week(date))
lookup_kwargs = {(u'%s__gte' % date_field): since, (u'%s__lt' % date_field): until}
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {u'week': date, u'next_week': self.get_next_week(date), u'previous_week': self.get_previous_week(date)})
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| 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())
return self._get_dated_items(date)
|
'Do the actual heavy lifting of getting the dated items; this accepts a
date object so that TodayArchiveView can be trivial.'
| def _get_dated_items(self, date):
| lookup_kwargs = self._make_single_date_lookup(date)
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {u'day': date, u'previous_day': self.get_previous_day(date), u'next_day': self.get_next_day(date), u'previous_month': self.get_previous_month(date), u'next_month': self.get_next_month(date)})
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| return self._get_dated_items(datetime.date.today())
|
'Get the object this request displays.'
| def get_object(self, queryset=None):
| 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())
qs = (queryset or self.get_queryset())
if ((not self.get_allow_future()) and (date > datetime.date.today())):
raise Http404((_(u'Future %(verbose_name_plural)s not available because %(class_name)s.allow_future is False.') % {u'verbose_name_plural': qs.model._meta.verbose_name_plural, u'class_name': self.__class__.__name__}))
lookup_kwargs = self._make_single_date_lookup(date)
qs = qs.filter(**lookup_kwargs)
return super(BaseDetailView, self).get_object(queryset=qs)
|
'Get the list of items for this view. This must be an iterable, and may
be a queryset (in which qs-specific behavior will be enabled).'
| def get_queryset(self):
| if (self.queryset is not None):
queryset = self.queryset
if hasattr(queryset, u'_clone'):
queryset = queryset._clone()
elif (self.model is not None):
queryset = self.model._default_manager.all()
else:
raise ImproperlyConfigured((u"'%s' must define 'queryset' or 'model'" % self.__class__.__name__))
return queryset
|
'Paginate the queryset, if needed.'
| def paginate_queryset(self, queryset, page_size):
| paginator = self.get_paginator(queryset, page_size, allow_empty_first_page=self.get_allow_empty())
page_kwarg = self.page_kwarg
page = (self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1)
try:
page_number = int(page)
except ValueError:
if (page == u'last'):
page_number = paginator.num_pages
else:
raise Http404(_(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())
except InvalidPage as e:
raise Http404((_(u'Invalid page (%(page_number)s): %(message)s') % {u'page_number': page_number, u'message': str(e)}))
|
'Get the number of items to paginate by, or ``None`` for no pagination.'
| def get_paginate_by(self, queryset):
| return self.paginate_by
|
'Return an instance of the paginator for this view.'
| def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True):
| return self.paginator_class(queryset, per_page, orphans=orphans, allow_empty_first_page=allow_empty_first_page)
|
'Returns ``True`` if the view should display empty lists, and ``False``
if a 404 should be raised instead.'
| def get_allow_empty(self):
| return self.allow_empty
|
'Get the name of the item to be used in the context.'
| def get_context_object_name(self, object_list):
| if self.context_object_name:
return self.context_object_name
elif hasattr(object_list, u'model'):
return (u'%s_list' % object_list.model._meta.object_name.lower())
else:
return None
|
'Get the context for this view.'
| def get_context_data(self, **kwargs):
| queryset = kwargs.pop(u'object_list')
page_size = self.get_paginate_by(queryset)
context_object_name = self.get_context_object_name(queryset)
if page_size:
(paginator, page, queryset, is_paginated) = self.paginate_queryset(queryset, page_size)
context = {u'paginator': paginator, u'page_obj': page, u'is_paginated': is_paginated, u'object_list': queryset}
else:
context = {u'paginator': None, u'page_obj': None, u'is_paginated': False, u'object_list': queryset}
if (context_object_name is not None):
context[context_object_name] = queryset
context.update(kwargs)
return super(MultipleObjectMixin, self).get_context_data(**context)
|
'Return 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.'
| def get_template_names(self):
| try:
names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
except ImproperlyConfigured:
names = []
if hasattr(self.object_list, u'model'):
opts = self.object_list.model._meta
names.append((u'%s/%s%s.html' % (opts.app_label, opts.object_name.lower(), self.template_name_suffix)))
return names
|
'Returns the initial data to use for forms on this view.'
| def get_initial(self):
| return self.initial.copy()
|
'Returns the form class to use in this view'
| def get_form_class(self):
| return self.form_class
|
'Returns an instance of the form to be used in this view.'
| def get_form(self, form_class):
| return form_class(**self.get_form_kwargs())
|
'Returns the keyword arguments for instantiating the form.'
| def get_form_kwargs(self):
| kwargs = {'initial': self.get_initial()}
if (self.request.method in ('POST', 'PUT')):
kwargs.update({'data': self.request.POST, 'files': self.request.FILES})
return kwargs
|
'Returns the supplied success URL.'
| def get_success_url(self):
| if self.success_url:
url = force_text(self.success_url)
else:
raise ImproperlyConfigured('No URL to redirect to. Provide a success_url.')
return url
|
'If the form is valid, redirect to the supplied URL.'
| def form_valid(self, form):
| return HttpResponseRedirect(self.get_success_url())
|
'If the form is invalid, re-render the context data with the
data-filled form and errors.'
| def form_invalid(self, form):
| return self.render_to_response(self.get_context_data(form=form))
|
'Returns the form class to use in this view.'
| def get_form_class(self):
| if self.form_class:
return self.form_class
else:
if (self.model is not None):
model = self.model
elif (hasattr(self, 'object') and (self.object is not None)):
model = self.object.__class__
else:
model = self.get_queryset().model
return model_forms.modelform_factory(model)
|
'Returns the keyword arguments for instantiating the form.'
| def get_form_kwargs(self):
| kwargs = super(ModelFormMixin, self).get_form_kwargs()
kwargs.update({'instance': self.object})
return kwargs
|
'Returns the supplied URL.'
| def get_success_url(self):
| if self.success_url:
url = (self.success_url % self.object.__dict__)
else:
try:
url = self.object.get_absolute_url()
except AttributeError:
raise ImproperlyConfigured('No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.')
return url
|
'If the form is valid, save the associated model.'
| def form_valid(self, form):
| self.object = form.save()
return super(ModelFormMixin, self).form_valid(form)
|
'If an object has been supplied, inject it into the context with the
supplied context_object_name name.'
| def get_context_data(self, **kwargs):
| context = {}
if self.object:
context['object'] = self.object
context_object_name = self.get_context_object_name(self.object)
if context_object_name:
context[context_object_name] = self.object
context.update(kwargs)
return super(ModelFormMixin, self).get_context_data(**context)
|
'Handles GET requests and instantiates a blank version of the form.'
| def get(self, request, *args, **kwargs):
| form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
|
'Handles POST requests, instantiating a form instance with the passed
POST variables and then checked for validity.'
| def post(self, request, *args, **kwargs):
| form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
|
'Calls the delete() method on the fetched object and then
redirects to the success URL.'
| def delete(self, request, *args, **kwargs):
| self.object = self.get_object()
self.object.delete()
return HttpResponseRedirect(self.get_success_url())
|
'This filter is to add safety in production environments (i.e. DEBUG
is False). If DEBUG is True then your site is not safe anyway.
This hook is provided as a convenience to easily activate or
deactivate the filter on a per request basis.'
| def is_active(self, request):
| return (settings.DEBUG is False)
|
'Replaces the values of POST parameters marked as sensitive with
stars (*********).'
| def get_post_parameters(self, request):
| if (request is None):
return {}
else:
sensitive_post_parameters = getattr(request, u'sensitive_post_parameters', [])
if (self.is_active(request) and sensitive_post_parameters):
cleansed = request.POST.copy()
if (sensitive_post_parameters == u'__ALL__'):
for (k, v) in cleansed.items():
cleansed[k] = CLEANSED_SUBSTITUTE
return cleansed
else:
for param in sensitive_post_parameters:
if (param in cleansed):
cleansed[param] = CLEANSED_SUBSTITUTE
return cleansed
else:
return request.POST
|
'Replaces the values of variables marked as sensitive with
stars (*********).'
| def get_traceback_frame_variables(self, request, tb_frame):
| current_frame = tb_frame.f_back
sensitive_variables = None
while (current_frame is not None):
if ((current_frame.f_code.co_name == u'sensitive_variables_wrapper') and (u'sensitive_variables_wrapper' in current_frame.f_locals)):
wrapper = current_frame.f_locals[u'sensitive_variables_wrapper']
sensitive_variables = getattr(wrapper, u'sensitive_variables', None)
break
current_frame = current_frame.f_back
cleansed = {}
if (self.is_active(request) and sensitive_variables):
if (sensitive_variables == u'__ALL__'):
for (name, value) in tb_frame.f_locals.items():
cleansed[name] = CLEANSED_SUBSTITUTE
else:
for (name, value) in tb_frame.f_locals.items():
if (name in sensitive_variables):
value = CLEANSED_SUBSTITUTE
elif isinstance(value, HttpRequest):
value = self.get_request_repr(value)
cleansed[name] = value
else:
for (name, value) in tb_frame.f_locals.items():
if isinstance(value, HttpRequest):
value = self.get_request_repr(value)
cleansed[name] = value
if ((tb_frame.f_code.co_name == u'sensitive_variables_wrapper') and (u'sensitive_variables_wrapper' in tb_frame.f_locals)):
cleansed[u'func_args'] = CLEANSED_SUBSTITUTE
cleansed[u'func_kwargs'] = CLEANSED_SUBSTITUTE
return cleansed.items()
|
'Return a Context instance containing traceback information.'
| def get_traceback_data(self):
| if (self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist)):
from django.template.loader import template_source_loaders
self.template_does_not_exist = True
self.loader_debug_info = []
for loader in template_source_loaders:
try:
source_list_func = loader.get_template_sources
template_list = [{u'name': t, u'exists': os.path.exists(t)} for t in source_list_func(str(self.exc_value))]
except AttributeError:
template_list = []
loader_name = ((loader.__module__ + u'.') + loader.__class__.__name__)
self.loader_debug_info.append({u'loader': loader_name, u'templates': template_list})
if (settings.TEMPLATE_DEBUG and hasattr(self.exc_value, u'django_template_source')):
self.get_template_exception_info()
frames = self.get_traceback_frames()
for (i, frame) in enumerate(frames):
if (u'vars' in frame):
frame[u'vars'] = [(k, force_escape(pprint(v))) for (k, v) in frame[u'vars']]
frames[i] = frame
unicode_hint = u''
if (self.exc_type and issubclass(self.exc_type, UnicodeError)):
start = getattr(self.exc_value, u'start', None)
end = getattr(self.exc_value, u'end', None)
if ((start is not None) and (end is not None)):
unicode_str = self.exc_value.args[1]
unicode_hint = smart_text(unicode_str[max((start - 5), 0):min((end + 5), len(unicode_str))], u'ascii', errors=u'replace')
from django import get_version
c = {u'is_email': self.is_email, u'unicode_hint': unicode_hint, u'frames': frames, u'request': self.request, u'filtered_POST': self.filter.get_post_parameters(self.request), u'settings': get_safe_settings(), u'sys_executable': sys.executable, u'sys_version_info': (u'%d.%d.%d' % sys.version_info[0:3]), u'server_time': datetime.datetime.now(), u'django_version_info': get_version(), u'sys_path': sys.path, u'template_info': self.template_info, u'template_does_not_exist': self.template_does_not_exist, u'loader_debug_info': self.loader_debug_info}
if self.exc_type:
c[u'exception_type'] = self.exc_type.__name__
if self.exc_value:
c[u'exception_value'] = smart_text(self.exc_value, errors=u'replace')
if frames:
c[u'lastframe'] = frames[(-1)]
return c
|
'Return HTML version of debug 500 HTTP error page.'
| def get_traceback_html(self):
| t = Template(TECHNICAL_500_TEMPLATE, name=u'Technical 500 template')
c = Context(self.get_traceback_data())
return t.render(c)
|
'Return plain text version of debug 500 HTTP error page.'
| def get_traceback_text(self):
| t = Template(TECHNICAL_500_TEXT_TEMPLATE, name=u'Technical 500 template')
c = Context(self.get_traceback_data(), autoescape=False)
return t.render(c)
|
'Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).'
| def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
| source = None
if ((loader is not None) and hasattr(loader, u'get_source')):
source = loader.get_source(module_name)
if (source is not None):
source = source.splitlines()
if (source is None):
try:
with open(filename, u'rb') as fp:
source = fp.readlines()
except (OSError, IOError):
pass
if (source is None):
return (None, [], None, [])
if isinstance(source[0], six.binary_type):
encoding = u'ascii'
for line in source[:2]:
match = re.search('coding[:=]\\s*([-\\w.]+)', line)
if match:
encoding = match.group(1).decode(u'ascii')
break
source = [six.text_type(sline, encoding, u'replace') for sline in source]
lower_bound = max(0, (lineno - context_lines))
upper_bound = (lineno + context_lines)
pre_context = [line.strip(u'\n') for line in source[lower_bound:lineno]]
context_line = source[lineno].strip(u'\n')
post_context = [line.strip(u'\n') for line in source[(lineno + 1):upper_bound]]
return (lower_bound, pre_context, context_line, post_context)
|
'Return the same data as from traceback.format_exception.'
| def format_exception(self):
| import traceback
frames = self.get_traceback_frames()
tb = [(f[u'filename'], f[u'lineno'], f[u'function'], f[u'context_line']) for f in frames]
list = [u'Traceback (most recent call last):\n']
list += traceback.format_list(tb)
list += traceback.format_exception_only(self.exc_type, self.exc_value)
return list
|
'Validates the given value and returns its "cleaned" value as an
appropriate Python object.
Raises ValidationError for any errors.'
| def clean(self, value):
| value = self.to_python(value)
self.validate(value)
self.run_validators(value)
return value
|
'Return the value that should be shown for this field on render of a
bound form, given the submitted POST data for the field and the initial
data, if any.
For most fields, this will simply be data; FileFields need to handle it
a bit differently.'
| def bound_data(self, data, initial):
| return data
|
'Given a Widget instance (*not* a Widget class), returns a dictionary of
any HTML attributes that should be added to the Widget, based on this
Field.'
| def widget_attrs(self, widget):
| return {}
|
'Returns a Unicode object.'
| def to_python(self, value):
| if (value in validators.EMPTY_VALUES):
return u''
return smart_text(value)
|
'Validates that int() can be called on the input. Returns the result
of int(). Returns None for empty values.'
| def to_python(self, value):
| value = super(IntegerField, self).to_python(value)
if (value in validators.EMPTY_VALUES):
return None
if self.localize:
value = formats.sanitize_separators(value)
try:
value = int(str(value))
except (ValueError, TypeError):
raise ValidationError(self.error_messages[u'invalid'])
return value
|
'Validates that float() can be called on the input. Returns the result
of float(). Returns None for empty values.'
| def to_python(self, value):
| value = super(IntegerField, self).to_python(value)
if (value in validators.EMPTY_VALUES):
return None
if self.localize:
value = formats.sanitize_separators(value)
try:
value = float(value)
except (ValueError, TypeError):
raise ValidationError(self.error_messages[u'invalid'])
return value
|
'Validates that the input is a decimal number. Returns a Decimal
instance. Returns None for empty values. Ensures that there are no more
than max_digits in the number, and no more than decimal_places digits
after the decimal point.'
| def to_python(self, value):
| if (value in validators.EMPTY_VALUES):
return None
if self.localize:
value = formats.sanitize_separators(value)
value = smart_text(value).strip()
try:
value = Decimal(value)
except DecimalException:
raise ValidationError(self.error_messages[u'invalid'])
return value
|
'Validates that the input can be converted to a date. Returns a Python
datetime.date object.'
| def to_python(self, value):
| if (value in validators.EMPTY_VALUES):
return None
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
return super(DateField, self).to_python(value)
|
'Validates that the input can be converted to a time. Returns a Python
datetime.time object.'
| def to_python(self, value):
| if (value in validators.EMPTY_VALUES):
return None
if isinstance(value, datetime.time):
return value
return super(TimeField, self).to_python(value)
|
'Validates that the input can be converted to a datetime. Returns a
Python datetime.datetime object.'
| def to_python(self, value):
| if (value in validators.EMPTY_VALUES):
return None
if isinstance(value, datetime.datetime):
return from_current_timezone(value)
if isinstance(value, datetime.date):
result = datetime.datetime(value.year, value.month, value.day)
return from_current_timezone(result)
if isinstance(value, list):
if (len(value) != 2):
raise ValidationError(self.error_messages[u'invalid'])
if ((value[0] in validators.EMPTY_VALUES) and (value[1] in validators.EMPTY_VALUES)):
return None
value = (u'%s %s' % tuple(value))
result = super(DateTimeField, self).to_python(value)
return from_current_timezone(result)
|
'regex can be either a string or a compiled regular expression object.
error_message is an optional error message to use, if
\'Enter a valid value\' is too generic for you.'
| def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
| if error_message:
error_messages = (kwargs.get(u'error_messages') or {})
error_messages[u'invalid'] = error_message
kwargs[u'error_messages'] = error_messages
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
self._set_regex(regex)
|
'Checks that the file-upload field data contains a valid image (GIF, JPG,
PNG, possibly others -- whatever the Python Imaging Library supports).'
| def to_python(self, data):
| f = super(ImageField, self).to_python(data)
if (f is None):
return None
try:
from PIL import Image
except ImportError:
import Image
if hasattr(data, u'temporary_file_path'):
file = data.temporary_file_path()
elif hasattr(data, u'read'):
file = BytesIO(data.read())
else:
file = BytesIO(data[u'content'])
try:
Image.open(file).verify()
except ImportError:
raise
except Exception:
raise ValidationError(self.error_messages[u'invalid_image'])
if (hasattr(f, u'seek') and callable(f.seek)):
f.seek(0)
return f
|
'Returns a Python boolean object.'
| def to_python(self, value):
| if (isinstance(value, six.string_types) and (value.lower() in (u'false', u'0'))):
value = False
else:
value = bool(value)
value = super(BooleanField, self).to_python(value)
if ((not value) and self.required):
raise ValidationError(self.error_messages[u'required'])
return value
|
'Explicitly checks for the string \'True\' and \'False\', which is what a
hidden field will submit for True and False, and for \'1\' and \'0\', which
is what a RadioField will submit. Unlike the Booleanfield we need to
explicitly check for True, because we are not using the bool() function'
| def to_python(self, value):
| if (value in (True, u'True', u'1')):
return True
elif (value in (False, u'False', u'0')):
return False
else:
return None
|
'Returns a Unicode object.'
| def to_python(self, value):
| if (value in validators.EMPTY_VALUES):
return u''
return smart_text(value)
|
'Validates that the input is in self.choices.'
| def validate(self, value):
| super(ChoiceField, self).validate(value)
if (value and (not self.valid_value(value))):
raise ValidationError((self.error_messages[u'invalid_choice'] % {u'value': value}))
|
'Check to see if the provided value is a valid choice'
| def valid_value(self, value):
| for (k, v) in self.choices:
if isinstance(v, (list, tuple)):
for (k2, v2) in v:
if (value == smart_text(k2)):
return True
elif (value == smart_text(k)):
return True
return False
|
'Validates that the value is in self.choices and can be coerced to the
right type.'
| def to_python(self, value):
| value = super(TypedChoiceField, self).to_python(value)
super(TypedChoiceField, self).validate(value)
if ((value == self.empty_value) or (value in validators.EMPTY_VALUES)):
return self.empty_value
try:
value = self.coerce(value)
except (ValueError, TypeError, ValidationError):
raise ValidationError((self.error_messages[u'invalid_choice'] % {u'value': value}))
return value
|
'Validates that the input is a list or tuple.'
| def validate(self, value):
| if (self.required and (not value)):
raise ValidationError(self.error_messages[u'required'])
for val in value:
if (not self.valid_value(val)):
raise ValidationError((self.error_messages[u'invalid_choice'] % {u'value': val}))
|
'Validates that the values are in self.choices and can be coerced to the
right type.'
| def to_python(self, value):
| value = super(TypedMultipleChoiceField, self).to_python(value)
super(TypedMultipleChoiceField, self).validate(value)
if ((value == self.empty_value) or (value in validators.EMPTY_VALUES)):
return self.empty_value
new_value = []
for choice in value:
try:
new_value.append(self.coerce(choice))
except (ValueError, TypeError, ValidationError):
raise ValidationError((self.error_messages[u'invalid_choice'] % {u'value': choice}))
return new_value
|
'Validates the given value against all of self.fields, which is a
list of Field instances.'
| def clean(self, value):
| super(ComboField, self).clean(value)
for field in self.fields:
value = field.clean(value)
return value
|
'Validates every value in the given list. A value is validated against
the corresponding Field in self.fields.
For example, if this MultiValueField was instantiated with
fields=(DateField(), TimeField()), clean() would call
DateField.clean(value[0]) and TimeField.clean(value[1]).'
| def clean(self, value):
| clean_data = []
errors = ErrorList()
if ((not value) or isinstance(value, (list, tuple))):
if ((not value) or (not [v for v in value if (v not in validators.EMPTY_VALUES)])):
if self.required:
raise ValidationError(self.error_messages[u'required'])
else:
return self.compress([])
else:
raise ValidationError(self.error_messages[u'invalid'])
for (i, field) in enumerate(self.fields):
try:
field_value = value[i]
except IndexError:
field_value = None
if (self.required and (field_value in validators.EMPTY_VALUES)):
raise ValidationError(self.error_messages[u'required'])
try:
clean_data.append(field.clean(field_value))
except ValidationError as e:
errors.extend(e.messages)
if errors:
raise ValidationError(errors)
out = self.compress(clean_data)
self.validate(out)
self.run_validators(out)
return out
|
'Returns a single value for the given list of values. The values can be
assumed to be valid.
For example, if this MultiValueField was instantiated with
fields=(DateField(), TimeField()), this might return a datetime
object created by combining the date and time in data_list.'
| def compress(self, data_list):
| raise NotImplementedError(u'Subclasses must implement this method.')
|
'Yields the forms in the order they should be rendered'
| def __iter__(self):
| return iter(self.forms)
|
'Returns the form at the given index, based on the rendering order'
| def __getitem__(self, index):
| return self.forms[index]
|
'All formsets have a management form which is not included in the length'
| def __bool__(self):
| return True
|
'Returns the ManagementForm instance for this FormSet.'
| @property
def management_form(self):
| if self.is_bound:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if (not form.is_valid()):
raise ValidationError(u'ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MAX_NUM_FORM_COUNT: self.max_num})
return form
|
'Returns the total number of forms in this FormSet.'
| def total_form_count(self):
| if self.is_bound:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
initial_forms = self.initial_form_count()
total_forms = (initial_forms + self.extra)
if (initial_forms > self.max_num >= 0):
total_forms = initial_forms
elif (total_forms > self.max_num >= 0):
total_forms = self.max_num
return total_forms
|
'Returns the number of forms that are required in this FormSet.'
| def initial_form_count(self):
| if self.is_bound:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
initial_forms = ((self.initial and len(self.initial)) or 0)
if (initial_forms > self.max_num >= 0):
initial_forms = self.max_num
return initial_forms
|
'Instantiates and returns the i-th form instance in a formset.'
| def _construct_form(self, i, **kwargs):
| defaults = {u'auto_id': self.auto_id, u'prefix': self.add_prefix(i), u'error_class': self.error_class}
if self.is_bound:
defaults[u'data'] = self.data
defaults[u'files'] = self.files
if (self.initial and (not (u'initial' in kwargs))):
try:
defaults[u'initial'] = self.initial[i]
except IndexError:
pass
if (i >= self.initial_form_count()):
defaults[u'empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
|
'Return a list of all the initial forms in this formset.'
| @property
def initial_forms(self):
| return self.forms[:self.initial_form_count()]
|
'Return a list of all the extra forms in this formset.'
| @property
def extra_forms(self):
| return self.forms[self.initial_form_count():]
|
'Returns a list of form.cleaned_data dicts for every form in self.forms.'
| @property
def cleaned_data(self):
| if (not self.is_valid()):
raise AttributeError((u"'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__))
return [form.cleaned_data for form in self.forms]
|
'Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.'
| @property
def deleted_forms(self):
| if ((not self.is_valid()) or (not self.can_delete)):
raise AttributeError((u"'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__))
if (not hasattr(self, u'_deleted_form_indexes')):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
if ((i >= self.initial_form_count()) and (not form.has_changed())):
continue
if self._should_delete_form(form):
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
|
'Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.'
| @property
def ordered_forms(self):
| if ((not self.is_valid()) or (not self.can_order)):
raise AttributeError((u"'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__))
if (not hasattr(self, u'_ordering')):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
if ((i >= self.initial_form_count()) and (not form.has_changed())):
continue
if (self.can_delete and self._should_delete_form(form)):
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
def compare_ordering_key(k):
if (k[1] is None):
return (1, 0)
return (0, k[1])
self._ordering.sort(key=compare_ordering_key)
return [self.forms[i[0]] for i in self._ordering]
|
'Returns an ErrorList of errors that aren\'t associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.'
| def non_form_errors(self):
| if (self._non_form_errors is not None):
return self._non_form_errors
return self.error_class()
|
'Returns a list of form.errors for every form in self.forms.'
| @property
def errors(self):
| if (self._errors is None):
self.full_clean()
return self._errors
|
'Returns whether or not the form was marked for deletion.'
| def _should_delete_form(self, form):
| return form.cleaned_data.get(DELETION_FIELD_NAME, False)
|
'Returns True if every form in self.forms is valid.'
| def is_valid(self):
| if (not self.is_bound):
return False
forms_valid = True
err = self.errors
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
if self._should_delete_form(form):
continue
forms_valid &= form.is_valid()
return (forms_valid and (not bool(self.non_form_errors())))
|
'Cleans all of self.data and populates self._errors.'
| def full_clean(self):
| self._errors = []
if (not self.is_bound):
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
try:
self.clean()
except ValidationError as e:
self._non_form_errors = self.error_class(e.messages)
|
'Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()'
| def clean(self):
| pass
|
'Returns true if data in any form differs from initial.'
| def has_changed(self):
| return any((form.has_changed() for form in self))
|
'A hook for adding extra fields on to each form instance.'
| def add_fields(self, form, index):
| if self.can_order:
if ((index is not None) and (index < self.initial_form_count())):
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=(index + 1), required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
|
'Returns True if the formset needs to be multipart, i.e. it
has FileInput. Otherwise, False.'
| def is_multipart(self):
| if self.forms:
return self.forms[0].is_multipart()
else:
return self.empty_form.is_multipart()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.