desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'First coerces all fields on this instance to their proper Python types. Then runs validation on every field. Returns a dictionary of field_name -> error_list.'
def validate(self):
error_dict = {} invalid_python = {} for f in self._meta.fields: try: setattr(self, f.attname, f.to_python(getattr(self, f.attname, f.get_default()))) except validators.ValidationError as e: error_dict[f.name] = e.messages invalid_python[f.name] = 1 for...
'Recursively populates seen_objs with all objects related to this object. When done, seen_objs will be in the format: {model_class: {pk_val: obj, pk_val: obj, ...}, model_class: {pk_val: obj, pk_val: obj, ...}, ...}'
def _collect_sub_objects(self, seen_objs):
pk_val = self._get_pk_val() if (pk_val in seen_objs.setdefault(self.__class__, {})): return seen_objs.setdefault(self.__class__, {})[pk_val] = self for related in self._meta.get_all_related_objects(): rel_opts_name = related.get_accessor_name() if isinstance(related.field.rel, On...
'Retrieve an item or slice from the set of results.'
def __getitem__(self, k):
if (not isinstance(k, (slice, int))): raise TypeError assert (((not isinstance(k, slice)) and (k >= 0)) or (isinstance(k, slice) and ((k.start is None) or (k.start >= 0)) and ((k.stop is None) or (k.stop >= 0)))), 'Negative indexing is not supported.' if (self._result_cache is None): ...
'Performs the SELECT database lookup of this QuerySet.'
def iterator(self):
try: (select, sql, params) = self._get_sql_clause() except EmptyResultSet: raise StopIteration extra_select = self._select.items() cursor = connection.cursor() cursor.execute(((('SELECT ' + ((self._distinct and 'DISTINCT ') or '')) + ','.join(select)) + sql), params) fill_c...
'Performs a SELECT COUNT() and returns the number of records as an integer. If the queryset is already cached (i.e. self._result_cache is set) this simply returns the length of the cached results set to avoid multiple SELECT COUNT(*) calls.'
def count(self):
if (self._result_cache is not None): return len(self._result_cache) counter = self._clone() counter._order_by = () counter._select_related = False offset = counter._offset limit = counter._limit counter._offset = None counter._limit = None try: (select, sql, params) =...
'Performs the SELECT and returns a single object matching the given keyword arguments.'
def get(self, *args, **kwargs):
clone = self.filter(*args, **kwargs) if (not clone._order_by): clone._order_by = () obj_list = list(clone) if (len(obj_list) < 1): raise self.model.DoesNotExist, ('%s matching query does not exist.' % self.model._meta.object_name) assert (len(obj_list) == 1), ('get() ...
'Create a new object with the given kwargs, saving it to the database and returning the created object.'
def create(self, **kwargs):
obj = self.model(**kwargs) obj.save() return obj
'Looks up an object with the given kwargs, creating one if necessary. Returns a tuple of (object, created), where created is a boolean specifying whether an object was created.'
def get_or_create(self, **kwargs):
assert len(kwargs), 'get_or_create() must be passed at least one keyword argument' defaults = kwargs.pop('defaults', {}) try: return (self.get(**kwargs), False) except self.model.DoesNotExist: params = dict([(k, v) for (k, v) in kwargs.items() if ('__' not in k)])...
'Returns the latest object, according to the model\'s \'get_latest_by\' option or optional given field_name.'
def latest(self, field_name=None):
latest_by = (field_name or self.model._meta.get_latest_by) assert bool(latest_by), "latest() requires either a field_name parameter or 'get_latest_by' in the model" assert ((self._limit is None) and (self._offset is None)), 'Cannot change a query once a slice ...
'Returns a dictionary mapping each of the given IDs to the object with that ID.'
def in_bulk(self, id_list):
assert ((self._limit is None) and (self._offset is None)), "Cannot use 'limit' or 'offset' with in_bulk" assert isinstance(id_list, (tuple, list)), 'in_bulk() must be provided with a list of IDs.' id_list = list(id_list) if (id_list == []): return {} ...
'Deletes the records in the current QuerySet.'
def delete(self):
assert ((self._limit is None) and (self._offset is None)), "Cannot use 'limit' or 'offset' with delete." del_query = self._clone() del_query._select_related = False del_query._order_by = [] more_objects = True while more_objects: seen_objs = SortedDict() more_ob...
'Returns a list of datetime objects representing all available dates for the given field_name, scoped to \'kind\'.'
def dates(self, field_name, kind, order='ASC'):
assert (kind in ('month', 'year', 'day')), "'kind' must be one of 'year', 'month' or 'day'." assert (order in ('ASC', 'DESC')), "'order' must be either 'ASC' or 'DESC'." field = self.model._meta.get_field(field_name, many_to_many=False) assert isinstance(field, ...
'Returns a new QuerySet instance with the args ANDed to the existing set.'
def filter(self, *args, **kwargs):
return self._filter_or_exclude(None, *args, **kwargs)
'Returns a new QuerySet instance with NOT (args) ANDed to the existing set.'
def exclude(self, *args, **kwargs):
return self._filter_or_exclude(QNot, *args, **kwargs)
'Returns a new QuerySet instance with filter_obj added to the filters. filter_obj can be a Q object (has \'get_sql\' method) or a dictionary of keyword lookup arguments.'
def complex_filter(self, filter_obj):
if hasattr(filter_obj, 'get_sql'): return self._filter_or_exclude(None, filter_obj) else: return self._filter_or_exclude(None, **filter_obj)
'Returns a new QuerySet instance with \'_select_related\' modified.'
def select_related(self, true_or_false=True, depth=0):
return self._clone(_select_related=true_or_false, _max_related_depth=depth)
'Returns a new QuerySet instance with the ordering changed.'
def order_by(self, *field_names):
assert ((self._limit is None) and (self._offset is None)), 'Cannot reorder a query once a slice has been taken.' return self._clone(_order_by=field_names)
'Returns a new QuerySet instance with \'_distinct\' modified.'
def distinct(self, true_or_false=True):
return self._clone(_distinct=true_or_false)
'Creates a negation of the q object passed in.'
def __init__(self, q):
self.q = q
'Returns a new QuerySet object. Subclasses can override this method to easily customise the behaviour of the Manager.'
def get_query_set(self):
return QuerySet(self.model)
'Returns the requested field by name. Raises FieldDoesNotExist on error.'
def get_field(self, name, many_to_many=True):
to_search = ((many_to_many and (self.fields + self.many_to_many)) or self.fields) for f in to_search: if (f.name == name): return f raise FieldDoesNotExist, ('%s has no field named %r' % (self.object_name, name))
'Returns the full \'ORDER BY\' clause for this object, according to self.ordering.'
def get_order_sql(self, table_prefix=''):
if (not self.ordering): return '' pre = ((table_prefix and (table_prefix + '.')) or '') return ('ORDER BY ' + orderlist2sql(self.ordering, self, pre))
'Returns a list of Options objects that are ordered with respect to this object.'
def get_ordered_objects(self):
if (not hasattr(self, '_ordered_objects')): objects = [] self._ordered_objects = objects return self._ordered_objects
'Returns True if this object\'s admin form has at least one of the given field_type (e.g. FileField).'
def has_field_type(self, field_type, follow=None):
if (not hasattr(self, '_field_types')): self._field_types = {} if (not self._field_types.has_key(field_type)): try: for f in self.fields: if isinstance(f, field_type): raise StopIteration for related in self.get_followed_related_objects...
'Returns a list of AdminFieldSet objects for this AdminOptions object.'
def get_field_sets(self, opts):
if (self.fields is None): field_struct = ((None, {'fields': [f.name for f in (opts.fields + opts.many_to_many) if (f.editable and (not isinstance(f, AutoField)))]}),) else: field_struct = self.fields new_fieldset_list = [] for fieldset in field_struct: fs_options = fieldset[1] ...
'Pull out the data meant for inline objects of this class, i.e. anything starting with our module name.'
def extract_data(self, data):
return data
'Get the list of this type of object from an instance of the parent class.'
def get_list(self, parent_instance=None):
if (parent_instance is not None): attr = getattr(parent_instance, self.get_accessor_name()) if self.field.rel.multiple: objects = list(attr.all()) count = (len(objects) + self.field.rel.num_extra_on_change) if self.field.rel.min_num_in_admin: count...
'Get the fields in this class that should be edited inline.'
def editable_fields(self):
return [f for f in (self.opts.fields + self.opts.many_to_many) if (f.editable and (f != self.field))]
'Converts the input value into the expected Python data type, raising validators.ValidationError if the data can\'t be converted. Returns the converted value. Subclasses should override this.'
def to_python(self, value):
return value
'Returns a list of errors for this field. This is the main interface, as it encapsulates some basic validation logic used by all fields. Subclasses should implement validate(), not validate_full().'
def validate_full(self, field_data, all_data):
if ((not self.blank) and (not field_data)): return [gettext_lazy('This field is required.')] try: self.validate(field_data, all_data) except validators.ValidationError as e: return e.messages return []
'Raises validators.ValidationError if field_data has any errors. Subclasses should override this to specify field-specific validation logic. This method should assume field_data has already been converted into the appropriate data type by Field.to_python().'
def validate(self, field_data, all_data):
pass
'Returns field\'s value just before saving.'
def pre_save(self, model_instance, add):
return getattr(model_instance, self.attname)
'Returns field\'s value prepared for saving into a database.'
def get_db_prep_save(self, value):
return value
'Returns field\'s value prepared for database lookup.'
def get_db_prep_lookup(self, lookup_type, value):
if (lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte', 'month', 'day', 'search')): return [value] elif (lookup_type in ('range', 'in')): return value elif (lookup_type in ('contains', 'icontains')): return [('%%%s%%' % prep_for_like_query(value))] elif (lookup_type == 'iexact'): ...
'Returns a boolean of whether this field has a default value.'
def has_default(self):
return (self.default is not NOT_PROVIDED)
'Returns the default value for this field.'
def get_default(self):
if (self.default is not NOT_PROVIDED): if callable(self.default): return self.default() return self.default if ((not self.empty_strings_allowed) or self.null): return None return ''
'Returns a list of field names that this object adds to the manipulator.'
def get_manipulator_field_names(self, name_prefix):
return [(name_prefix + self.name)]
'Returns a list of oldforms.FormField instances for this field. It calculates the choices at runtime, not at compile time. name_prefix is a prefix to prepend to the "field_name" argument. rel is a boolean specifying whether this field is in a related context.'
def get_manipulator_fields(self, opts, manipulator, change, name_prefix='', rel=False, follow=True):
(field_objs, params) = self.prepare_field_objs_and_params(manipulator, name_prefix) for field_name_list in opts.unique_together: if (field_name_list[0] == self.name): params['validator_list'].append(getattr(manipulator, ('isUnique%s' % '_'.join(field_name_list)))) if self.unique_for_date...
'Given the full new_data dictionary (from the manipulator), returns this field\'s data.'
def get_manipulator_new_data(self, new_data, rel=False):
if rel: return new_data.get(self.name, [self.get_default()])[0] val = new_data.get(self.name, self.get_default()) if ((not self.empty_strings_allowed) and (val == '') and self.null): val = None return val
'Returns a list of tuples used as SelectField choices for this field.'
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH):
first_choice = ((include_blank and blank_choice) or []) if self.choices: return (first_choice + list(self.choices)) rel_model = self.rel.to if hasattr(self.rel, 'get_related_field'): lst = [(getattr(x, self.rel.get_related_field().attname), str(x)) for x in rel_model._default_manager.com...
'Returns a dictionary mapping the field\'s manipulator field names to its "flattened" string values for the admin view. obj is the instance to extract the values from.'
def flatten_data(self, follow, obj=None):
return {self.attname: self._get_val_from_obj(obj)}
'Returns a django.newforms.Field instance for this database Field.'
def formfield(self, **kwargs):
defaults = {'required': (not self.blank), 'label': capfirst(self.verbose_name), 'help_text': self.help_text} defaults.update(kwargs) return forms.CharField(**defaults)
'Returns the value of this field in the given model instance.'
def value_from_object(self, obj):
return getattr(obj, self.attname)
'Function that can be curried to provide the m2m table name for this relation'
def _get_m2m_db_table(self, opts):
if self.db_table: return self.db_table else: return ('%s_%s' % (opts.db_table, self.name))
'Function that can be curried to provide the source column name for the m2m table'
def _get_m2m_column_name(self, related):
if (related.model == related.parent_model): return (('from_' + related.model._meta.object_name.lower()) + '_id') else: return (related.model._meta.object_name.lower() + '_id')
'Function that can be curried to provide the related column name for the m2m table'
def _get_m2m_reverse_name(self, related):
if (related.model == related.parent_model): return (('to_' + related.parent_model._meta.object_name.lower()) + '_id') else: return (related.parent_model._meta.object_name.lower() + '_id')
'Validates that the value is a valid list of foreign keys'
def isValidIDList(self, field_data, all_data):
mod = self.rel.to try: pks = map(int, field_data.split(',')) except ValueError: return objects = mod._default_manager.in_bulk(pks) if (len(objects) != len(pks)): badkeys = [k for k in pks if (k not in objects)] raise validators.ValidationError, (ngettext('Please en...
'Returns the value of this field in the given model instance.'
def value_from_object(self, obj):
return getattr(obj, self.attname).all()
'Returns the Field in the \'to\' object to which this relationship is tied.'
def get_related_field(self):
return self.to._meta.get_field(self.field_name)
'Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW'
def process_request(self, request):
if request.META.has_key('HTTP_USER_AGENT'): for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(request.META['HTTP_USER_AGENT']): return http.HttpResponseForbidden('<h1>Forbidden</h1>') host = http.get_host(request) old_url = [host, request...
'Check for a flat page (for 404s) and calculate the Etag, if needed.'
def process_response(self, request, response):
if (response.status_code == 404): if settings.SEND_BROKEN_LINK_EMAILS: domain = http.get_host(request) referer = request.META.get('HTTP_REFERER', None) is_internal = _is_internal_request(domain, referer) path = request.get_full_path() if (referer a...
'Enters transaction management'
def process_request(self, request):
transaction.enter_transaction_management() transaction.managed(True)
'Rolls back the database and leaves transaction management'
def process_exception(self, request, exception):
if transaction.is_dirty(): transaction.rollback() transaction.leave_transaction_management()
'Commits and leaves transaction management.'
def process_response(self, request, response):
if transaction.is_managed(): if transaction.is_dirty(): transaction.commit() transaction.leave_transaction_management() return response
'If the request method is HEAD and either the IP is internal or the user is a logged-in staff member, quickly return with an x-header indicating the view function. This is used by the documentation module to lookup the view function for an arbitrary page.'
def process_view(self, request, view_func, view_args, view_kwargs):
if ((request.method == 'HEAD') and ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS) or (request.user.is_authenticated() and request.user.is_staff))): response = http.HttpResponse() response['X-View'] = ('%s.%s' % (view_func.__module__, view_func.__name__)) return response
'Checks whether the page is already cached and returns the cached version if available.'
def process_request(self, request):
if self.cache_anonymous_only: assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth....
'Sets the cache, if needed.'
def process_response(self, request, response):
if ((not hasattr(request, '_cache_update_cache')) or (not request._cache_update_cache)): return response if (request.method != 'GET'): return response if (not (response.status_code == 200)): return response patch_response_headers(response, self.cache_timeout) cache_key = lear...
'Looks up field by field name; raises KeyError on failure'
def __getitem__(self, field_name):
for field in self.fields: if (field.field_name == field_name): return field raise KeyError, ('Field %s not found\n%s' % (field_name, repr(self.fields)))
'Deletes the field with the given field name; raises KeyError on failure'
def __delitem__(self, field_name):
for (i, field) in enumerate(self.fields): if (field.field_name == field_name): del self.fields[i] return raise KeyError, ('Field %s not found' % field_name)
'Confirms user has required permissions to use this manipulator; raises PermissionDenied on failure.'
def check_permissions(self, user):
if (self.required_permission is None): return if user.has_perm(self.required_permission): return raise PermissionDenied
'Makes any necessary preparations to new_data, in place, before data has been validated.'
def prepare(self, new_data):
for field in self.fields: field.prepare(new_data)
'Returns dictionary mapping field_names to error-message lists'
def get_validation_errors(self, new_data):
errors = {} self.prepare(new_data) for field in self.fields: errors.update(field.get_validation_errors(new_data)) val_name = ('validate_%s' % field.field_name) if hasattr(self, val_name): val = getattr(self, val_name) try: field.run_validator(n...
'Saves the changes and returns the new object'
def save(self, new_data):
raise NotImplementedError
'Convert the data from HTML data types to Python datatypes, changing the object in place. This happens after validation but before storage. This must happen after validation because html2python functions aren\'t expected to deal with invalid input.'
def do_html2python(self, new_data):
for field in self.fields: field.convert_post_data(new_data)
'Renders the field'
def __str__(self):
return str(self.formfield.render(self.data))
'Like __str__(), but returns a list. Use this when the field\'s render() method returns a list.'
def field_list(self):
return self.formfield.render(self.data)
'Look up field by template key; raise KeyError on failure'
def __getitem__(self, template_key):
return self.formfield_dict[template_key]
'Returns list of all errors in this collection\'s formfields'
def errors(self):
errors = [] for field in self.formfield_dict.values(): if hasattr(field, 'errors'): errors.extend(field.errors()) return errors
'Hook for doing something to new_data (in place) before validation.'
def prepare(self, new_data):
pass
'Hook for converting an HTML datatype (e.g. \'on\' for checkboxes) to a Python type'
def html2python(data):
return data
'Returns the HTML \'id\' attribute for this form field.'
def get_id(self):
return (FORM_FIELD_ID_PREFIX + self.field_name)
'Convert value from browser (\'on\' or \'\') to a Python boolean'
def html2python(data):
if (data == 'on'): return True return False
'Returns a special object, RadioFieldRenderer, that is iterable *and* has a default str() rendered output. This allows for flexible use in templates. You can just use the default rendering: {{ field_name }} ...which will output the radio buttons in an unordered list. Or, you can manually traverse each radio option for ...
def render(self, data):
class RadioFieldRenderer: def __init__(self, datalist, ul_class): (self.datalist, self.ul_class) = (datalist, ul_class) def __str__(self): 'Default str() output for this radio field -- a <ul>' output = [('<ul%s>' % ((self.ul_class and ('...
'Converts the field into a datetime.datetime object'
def html2python(data):
import datetime try: (date, time) = data.split() (y, m, d) = date.split('-') timebits = time.split(':') (h, mn) = timebits[:2] if (len(timebits) > 2): s = int(timebits[2]) else: s = 0 return datetime.datetime(int(y), int(m), int(d),...
'Converts the field into a datetime.date object'
def html2python(data):
import time, datetime try: time_tuple = time.strptime(data, '%Y-%m-%d') return datetime.date(*time_tuple[0:3]) except (ValueError, TypeError): return None
'Converts the field into a datetime.time object'
def html2python(data):
import time, datetime try: part_list = data.split('.') try: time_tuple = time.strptime(part_list[0], '%H:%M:%S') except ValueError: time_tuple = time.strptime(part_list[0], '%H:%M') t = datetime.time(*time_tuple[3:6]) if (len(part_list) == 2): ...
'ValidationError can be passed a string or a list.'
def __init__(self, message):
if isinstance(message, list): self.messages = ErrorList([smart_unicode(msg) for msg in message]) else: assert isinstance(message, basestring), ('%s should be a basestring' % repr(message)) message = smart_unicode(message) self.messages = ErrorList([message])
'Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors.'
def clean(self, value):
if (self.required and (value in EMPTY_VALUES)): raise ValidationError(gettext(u'This field is required.')) return value
'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 {}
'Validates max_length and min_length. Returns a Unicode object.'
def clean(self, value):
super(CharField, self).clean(value) if (value in EMPTY_VALUES): return u'' value = smart_unicode(value) if ((self.max_length is not None) and (len(value) > self.max_length)): raise ValidationError((gettext(u'Ensure this value has at most %d characters.') % self.max_l...
'Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values.'
def clean(self, value):
super(IntegerField, self).clean(value) if (value in EMPTY_VALUES): return None try: value = int(value) except (ValueError, TypeError): raise ValidationError(gettext(u'Enter a whole number.')) if ((self.max_value is not None) and (value > self.max_value)): rai...
'Validates that the input can be converted to a date. Returns a Python datetime.date object.'
def clean(self, value):
super(DateField, self).clean(value) if (value in 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: try: return datetime.date(*time.str...
'Validates that the input can be converted to a time. Returns a Python datetime.time object.'
def clean(self, value):
super(TimeField, self).clean(value) if (value in EMPTY_VALUES): return None if isinstance(value, datetime.time): return value for format in self.input_formats: try: return datetime.time(*time.strptime(value, format)[3:6]) except ValueError: continu...
'Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.'
def clean(self, value):
super(DateTimeField, self).clean(value) if (value in 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) for format in self.input_formats: tr...
'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):
super(RegexField, self).__init__(*args, **kwargs) if isinstance(regex, basestring): regex = re.compile(regex) self.regex = regex (self.max_length, self.min_length) = (max_length, min_length) self.error_message = (error_message or gettext(u'Enter a valid value.'))
'Validates that the input matches the regular expression. Returns a Unicode object.'
def clean(self, value):
super(RegexField, self).clean(value) if (value in EMPTY_VALUES): value = u'' value = smart_unicode(value) if (value == u''): return value if ((self.max_length is not None) and (len(value) > self.max_length)): raise ValidationError((gettext(u'Ensure this value has ...
'Returns a Python boolean object.'
def clean(self, value):
super(BooleanField, self).clean(value) return bool(value)
'Validates that the input is in self.choices.'
def clean(self, value):
value = super(ChoiceField, self).clean(value) if (value in EMPTY_VALUES): value = u'' value = smart_unicode(value) if (value == u''): return value valid_values = set([str(k) for (k, v) in self.choices]) if (value not in valid_values): raise ValidationError(gettext(u'Selec...
'Validates that the input is a list or tuple.'
def clean(self, value):
if (self.required and (not value)): raise ValidationError(gettext(u'This field is required.')) elif ((not self.required) and (not value)): return [] if (not isinstance(value, (list, tuple))): raise ValidationError(gettext(u'Enter a list of values.')) new_valu...
'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 (self.required and (not value)): raise ValidationError(gettext(u'This field is required.')) elif ((not self.required) and (not value)): return self.compress([]) if (not isinstance(value, (list, tuple))): raise ValidationError(g...
'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.')
'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, name):
return data.get(name, None)
'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_
'Outputs a <ul> for this set of radio fields.'
def __unicode__(self):
return (u'<ul>\n%s\n</ul>' % u'\n'.join([(u'<li>%s</li>' % w) for w in self]))
'Returns a RadioFieldRenderer instance rather than a Unicode string.'
def render(self, name, value, attrs=None, choices=()):
if (value is None): value = '' str_value = smart_unicode(value) attrs = (attrs or {}) return RadioFieldRenderer(name, str_value, attrs, list(chain(self.choices, choices)))
'Returns a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty.'
def decompress(self, value):
raise NotImplementedError('Subclasses must implement this method.')
'Returns a BoundField with the given name.'
def __getitem__(self, name):
try: field = self.fields[name] except KeyError: raise KeyError(('Key %r not found in Form' % name)) return BoundField(self, field, name)