desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get the previous valid month.'
| def get_previous_month(self, date):
| (first_day, last_day) = _month_bounds(date)
prev = (first_day - datetime.timedelta(days=1))
return _get_next_prev_month(self, prev, is_previous=True, use_first_day=True)
|
'Get a day format string in strptime syntax to be used to parse the day
from url variables.'
| def get_day_format(self):
| return self.day_format
|
'Return the day for which this view should display data'
| def get_day(self):
| day = self.day
if (day is None):
try:
day = self.kwargs['day']
except KeyError:
try:
day = self.request.GET['day']
except KeyError:
raise Http404(_(u'No day specified'))
return day
|
'Get the next valid day.'
| def get_next_day(self, date):
| next = (date + datetime.timedelta(days=1))
return _get_next_prev_month(self, next, is_previous=False, use_first_day=False)
|
'Get the previous valid day.'
| def get_previous_day(self, date):
| prev = (date - datetime.timedelta(days=1))
return _get_next_prev_month(self, prev, is_previous=True, use_first_day=False)
|
'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['week']
except KeyError:
try:
week = self.request.GET['week']
except KeyError:
raise Http404(_(u'No week specified'))
return week
|
'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
|
'Obtain the list of dates and itesm'
| def get_dated_items(self):
| raise NotImplementedError('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, **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()
if (not allow_future):
qs = qs.filter(**{('%s__lte' % date_field): datetime.datetime.now()})
if ((not allow_empty) and (not qs)):
... |
'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):
| date_field = self.get_date_field()
allow_empty = self.get_allow_empty()
date_list = queryset.dates(date_field, date_type)[::(-1)]
if ((date_list is not None) and (not date_list) and (not allow_empty)):
name = force_unicode(queryset.model._meta.verbose_name_plural)
raise Http404((_(u'No ... |
'Get the context. Must return a Context (or subclass) instance.'
| def get_context_data(self, **kwargs):
| items = kwargs.pop('object_list')
context = super(BaseDateListView, self).get_context_data(object_list=items)
context.update(kwargs)
return context
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| qs = self.get_dated_queryset()
date_list = self.get_date_list(qs, 'year')
if date_list:
object_list = qs.order_by(('-' + self.get_date_field()))
else:
object_list = qs.none()
return (date_list, object_list, {})
|
'Return (date_list, items, extra_context) for this request.'
| def get_dated_items(self):
| year = self.get_year()
date_field = self.get_date_field()
qs = self.get_dated_queryset(**{(date_field + '__year'): year})
date_list = self.get_date_list(qs, 'month')
if self.get_make_object_list():
object_list = qs.order_by(('-' + date_field))
else:
object_list = qs.none()
re... |
'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())
(first_day, last_day) = _month_bounds(date)
lookup_kwargs = {('%s__gte' % date_field): first_day, ('%s__lt' % date_field): las... |
'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 = {'%W': '1', '%U': '0'}[week_format]
date = _date_from_string(year, self.get_year_format(), week_start, '%w', week, week_format)
first_day = date
last_day = (... |
'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):
| date_field = self.get_date_field()
field = self.get_queryset().model._meta.get_field(date_field)
lookup_kwargs = _date_lookup_for_field(field, date)
qs = self.get_dated_queryset(**lookup_kwargs)
return (None, qs, {'day': date, 'previous_day': self.get_previous_day(date), 'next_day': self.get_next_da... |
'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 = self.get_queryset()
if ((not self.get_allow_future()) and (date > datetime.date.today())):
raise Ht... |
'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).'
| def get_queryset(self):
| if (self.queryset is not None):
queryset = self.queryset
if hasattr(queryset, '_clone'):
queryset = queryset._clone()
elif (self.model is not None):
queryset = self.model._default_manager.all()
else:
raise ImproperlyConfigured((u"'%s' must define 'queryse... |
'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 = (self.kwargs.get('page') or self.request.GET.get('page') or 1)
try:
page_number = int(page)
except ValueError:
if (page == 'last'):
page_number = paginator.num_pages
... |
'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, 'model'):
return smart_str(('%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('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 = {'paginator': paginator, 'page_obj'... |
'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.'
| def get_template_names(self):
| try:
names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
except ImproperlyConfigured:
names = []
if hasattr(self.object_list, 'model'):
opts = self.object_list.model._meta
names.append(('%s/%s%s.html' % (opts.app_label, opts.object_name.lower(), self... |
'Returns the initial data to use for forms on this view.'
| def get_initial(self):
| return self.initial
|
'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 instanciating 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 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 ... |
'Returns the keyword arguments for instanciating the form.'
| def get_form_kwargs(self):
| kwargs = super(ModelFormMixin, self).get_form_kwargs()
kwargs.update({'instance': self.object})
return kwargs
|
'Return HTML code for traceback.'
| def get_traceback_html(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:
module = import_m... |
'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, 'get_source')):
source = loader.get_source(module_name)
if (source is not None):
source = source.splitlines()
if (source is None):
try:
f = open(filename)
try:
source = f.re... |
'Return the same data as from traceback.format_exception.'
| def format_exception(self):
| import traceback
frames = self.get_traceback_frames()
tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames]
list = ['Traceback (most recent call last):\n']
list += traceback.format_list(tb)
list += traceback.format_exception_only(self.exc_type, self.ex... |
'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_unicode(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['i... |
'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['inva... |
'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_str(value).strip()
try:
value = Decimal(value)
except DecimalException:
raise ValidationError(self.error_messages['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
for format in (self.input_formats or formats.get_format('DATE_INPUT_FORMATS')):
try:
return dateti... |
'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
for format in (self.input_formats or formats.get_format('TIME_INPUT_FORMATS')):
try:
return datetime.time(*time.strptime(value, format)[3:6])
except ValueError:
... |
'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 value
if isinstance(value, datetime.date):
return datetime.datetime(value.year, value.month, value.day)
if isinstance(value, list):
if (len(value) != 2):
raise V... |
'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('error_messages') or {})
error_messages['invalid'] = error_message
kwargs['error_messages'] = error_messages
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
if isinstance(regex, basestring):
regex = re.c... |
'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, 'temporary_file_path'):
file = data.temporary_file_path()
elif hasattr(data, 'read'):
file = StringIO(data.... |
'Returns a Python boolean object.'
| def to_python(self, value):
| if (value in ('False', '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['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, 'True', '1')):
return True
elif (value in (False, 'False', '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_unicode(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['invalid_choice'] % {'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_unicode(k2)):
return True
elif (value == smart_unicode(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):
... |
'Validates that the input is a list or tuple.'
| def validate(self, value):
| if (self.required and (not value)):
raise ValidationError(self.error_messages['required'])
for val in value:
if (not self.valid_value(val)):
raise ValidationError((self.error_messages['invalid_choice'] % {'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(s... |
'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['required'])
else:
... |
'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('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 list(self)[index]
|
'Returns the ManagementForm instance for this FormSet.'
| 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('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, p... |
'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... |
'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 = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.is_bound:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial:
try:
defaults['initial'] = self.initial[i]
except IndexError:
pass
if (i >= self.initi... |
'Return a list of all the initial forms in this formset.'
| def _get_initial_forms(self):
| return self.forms[:self.initial_form_count()]
|
'Return a list of all the extra forms in this formset.'
| def _get_extra_forms(self):
| return self.forms[self.initial_form_count():]
|
'Returns a list of form.cleaned_data dicts for every form in self.forms.'
| def _get_cleaned_data(self):
| if (not self.is_valid()):
raise AttributeError(("'%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.'
| def _get_deleted_forms(self):
| if ((not self.is_valid()) or (not self.can_delete)):
raise AttributeError(("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__))
if (not hasattr(self, '_deleted_form_indexes')):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count())... |
'Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.'
| def _get_ordered_forms(self):
| if ((not self.is_valid()) or (not self.can_order)):
raise AttributeError(("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__))
if (not hasattr(self, '_ordering')):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self... |
'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.'
| def _get_errors(self):
| if (self._errors is None):
self.full_clean()
return self._errors
|
'Returns True if form.errors is empty for every form in self.forms.'
| 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
if bool(self.errors[i]):
form... |
'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
|
'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... |
'Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.'
| def is_multipart(self):
| return (self.forms and self.forms[0].is_multipart())
|
'Returns this formset rendered as HTML <tr>s -- excluding the <table></table>.'
| def as_table(self):
| forms = u' '.join([form.as_table() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
'Returns this formset rendered as HTML <p>s.'
| def as_p(self):
| forms = u' '.join([form.as_p() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
'Returns this formset rendered as HTML <li>s.'
| def as_ul(self):
| forms = u' '.join([form.as_ul() for form in self])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
|
'For backwards-compatibility, several types of fields need to be
excluded from model validation. See the following tickets for
details: #12507, #12521, #12553'
| def _get_validation_exclusions(self):
| exclude = []
for f in self.instance._meta.fields:
field = f.name
if (field not in self.fields):
exclude.append(f.name)
elif (self._meta.fields and (field not in self._meta.fields)):
exclude.append(f.name)
elif (self._meta.exclude and (field in self._meta.e... |
'Calls the instance\'s validate_unique() method and updates the form\'s
validation errors if any were raised.'
| def validate_unique(self):
| exclude = self._get_validation_exclusions()
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError as e:
self._update_errors(e.message_dict)
|
'Saves this ``form``\'s cleaned_data into model instance
``self.instance``.
If commit=True, then the changes to ``instance`` will be saved to the
database. Returns ``instance``.'
| def save(self, commit=True):
| if (self.instance.pk is None):
fail_message = 'created'
else:
fail_message = 'changed'
return save_instance(self, self.instance, self._meta.fields, fail_message, commit, construct=False)
|
'Returns the number of forms that are required in this FormSet.'
| def initial_form_count(self):
| if (not (self.data or self.files)):
return len(self.get_queryset())
return super(BaseModelFormSet, self).initial_form_count()
|
'Saves and returns a new model instance for the given form.'
| def save_new(self, form, commit=True):
| return form.save(commit=commit)
|
'Saves and returns an existing model instance for the given form.'
| def save_existing(self, form, instance, commit=True):
| return form.save(commit=commit)
|
'Saves model instances for every form, adding and changing instances
as necessary, and returns the list of instances.'
| def save(self, commit=True):
| if (not commit):
self.saved_forms = []
def save_m2m():
for form in self.saved_forms:
form.save_m2m()
self.save_m2m = save_m2m
return (self.save_existing_objects(commit) + self.save_new_objects(commit))
|
'Add a hidden field for the object\'s primary key.'
| def add_fields(self, form, index):
| from django.db.models import AutoField, OneToOneField, ForeignKey
self._pk_field = pk = self.model._meta.pk
def pk_is_not_editable(pk):
return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk)))
if (p... |
'This method is used to convert objects into strings; it\'s used to
generate the labels for the choices presented by this object. Subclasses
can override this method to customize the display of the choices.'
| def label_from_instance(self, obj):
| return smart_unicode(obj)
|
'Returns a Media object that only contains media of the given type'
| def __getitem__(self, name):
| if (name in MEDIA_TYPES):
return Media(**{str(name): getattr(self, ('_' + name))})
raise KeyError(('Unknown media type "%s"' % name))
|
'Returns this Widget rendered as HTML, as a Unicode string.
The \'value\' given is not guaranteed to be valid input, so subclass
implementations should program defensively.'
| def render(self, name, value, attrs=None):
| raise NotImplementedError
|
'Helper function for building an attribute dictionary.'
| def build_attrs(self, extra_attrs=None, **kwargs):
| attrs = dict(self.attrs, **kwargs)
if extra_attrs:
attrs.update(extra_attrs)
return attrs
|
'Given a dictionary of data and this widget\'s name, returns the value
of this widget. Returns None if it\'s not provided.'
| def value_from_datadict(self, data, files, name):
| return data.get(name, None)
|
'Return True if data differs from initial.'
| def _has_changed(self, initial, data):
| if (data is None):
data_value = u''
else:
data_value = data
if (initial is None):
initial_value = u''
else:
initial_value = initial
if (force_unicode(initial_value) != force_unicode(data_value)):
return True
return False
|
'Returns the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Returns None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
return an ID value that corresponds to the first ID in the ... | def id_for_label(self, id_):
| return id_
|
'File widgets take data from FILES, not POST'
| def value_from_datadict(self, data, files, name):
| return files.get(name, None)
|
'Given the name of the file input, return the name of the clear checkbox
input.'
| def clear_checkbox_name(self, name):
| return (name + '-clear')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.