desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'All inline references are pending under MySQL'
def sql_for_inline_foreign_key_references(self, field, known_models, style):
return ([], True)
'Returns a list of table names in the current database.'
def get_table_list(self, cursor):
cursor.execute('SHOW TABLES') return [row[0] for row in cursor.fetchall()]
'Returns a description of the table, with the DB-API cursor.description interface.'
def get_table_description(self, cursor, table_name):
cursor.execute(('SELECT * FROM %s LIMIT 1' % self.connection.ops.quote_name(table_name))) return cursor.description
'Returns a dictionary of {field_name: field_index} for the given table. Indexes are 0-based.'
def _name_to_index(self, cursor, table_name):
return dict([(d[0], i) for (i, d) in enumerate(self.get_table_description(cursor, table_name))])
'Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based.'
def get_relations(self, cursor, table_name):
my_field_dict = self._name_to_index(cursor, table_name) constraints = [] relations = {} try: cursor.execute('\n SELECT column_name, referenced_table_name, referenced_column_name\n ...
'Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {\'primary_key\': boolean representing whether it\'s the primary key, \'unique\': boolean representing whether it\'s a unique index}'
def get_indexes(self, cursor, table_name):
cursor.execute(('SHOW INDEX FROM %s' % self.connection.ops.quote_name(table_name))) indexes = {} for row in cursor.fetchall(): indexes[row[4]] = {'primary_key': (row[2] == 'PRIMARY'), 'unique': (not bool(row[1]))} return indexes
'Check that the backend fully supports the provided aggregate. The population and sample statistics (STDDEV_POP, STDDEV_SAMP, VAR_POP, VAR_SAMP) were first implemented in Postgres 8.2. The implementation of population statistics (STDDEV_POP and VAR_POP) under Postgres 8.2 - 8.2.4 is known to be faulty. Raise NotImpleme...
def check_aggregate_support(self, aggregate):
if (aggregate.sql_function in ('STDDEV_POP', 'STDDEV_SAMP', 'VAR_POP', 'VAR_SAMP')): if (self.postgres_version[0:2] < (8, 2)): raise NotImplementedError(('PostgreSQL does not support %s prior to version 8.2. Please upgrade your version of PostgreSQL.' % ...
'Returns the maximum length of an identifier. Note that the maximum length of an identifier is 63 by default, but can be changed by recompiling PostgreSQL after editing the NAMEDATALEN macro in src/include/pg_config_manual.h . This implementation simply returns 63, but can easily be overridden by a custom database back...
def max_name_length(self):
return 63
'Returns a list of table names in the current database.'
def get_table_list(self, cursor):
cursor.execute("\n SELECT c.relname\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n ...
'Returns a description of the table, with the DB-API cursor.description interface.'
def get_table_description(self, cursor, table_name):
cursor.execute(('SELECT * FROM %s LIMIT 1' % self.connection.ops.quote_name(table_name))) return cursor.description
'Returns a dictionary of {field_index: (field_index_other_table, other_table)} representing all relationships to the given table. Indexes are 0-based.'
def get_relations(self, cursor, table_name):
cursor.execute("\n SELECT con.conkey, con.confkey, c2.relname\n FROM pg_constraint con, pg_class c1, pg_class c2\n WHERE c1.oid = con.conre...
'Returns a dictionary of fieldname -> infodict for the given table, where each infodict is in the format: {\'primary_key\': boolean representing whether it\'s the primary key, \'unique\': boolean representing whether it\'s a unique index}'
def get_indexes(self, cursor, table_name):
cursor.execute('\n SELECT attr.attname, idx.indkey, idx.indisunique, idx.indisprimary\n FROM pg_catalog.pg_class c, pg_catalog.pg_class c2,\n ...
'Generates a 32-bit digest of a set of arguments that can be used to shorten identifying names.'
def _digest(self, *args):
return ('%x' % (abs(hash(args)) % 4294967296L))
'Returns the SQL required to create a single model, as a tuple of: (list_of_sql, pending_references_dict)'
def sql_create_model(self, model, style, known_models=set()):
from django.db import models opts = model._meta if ((not opts.managed) or opts.proxy): return ([], {}) final_output = [] table_output = [] pending_references = {} qn = self.connection.ops.quote_name for f in opts.local_fields: col_type = f.db_type(connection=self.connecti...
'Return the SQL snippet defining the foreign key reference for a field'
def sql_for_inline_foreign_key_references(self, field, known_models, style):
qn = self.connection.ops.quote_name if (field.rel.to in known_models): output = [((((((style.SQL_KEYWORD('REFERENCES') + ' ') + style.SQL_TABLE(qn(field.rel.to._meta.db_table))) + ' (') + style.SQL_FIELD(qn(field.rel.to._meta.get_field(field.rel.field_name).column))) + ')') + self.connection.ops.d...
'Returns any ALTER TABLE statements to add constraints after the fact.'
def sql_for_pending_references(self, model, style, pending_references):
from django.db.backends.util import truncate_name if ((not model._meta.managed) or model._meta.proxy): return [] qn = self.connection.ops.quote_name final_output = [] opts = model._meta if (model in pending_references): for (rel_class, f) in pending_references[model]: ...
'Return the CREATE TABLE statments for all the many-to-many tables defined on a model'
def sql_for_many_to_many(self, model, style):
import warnings warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', PendingDeprecationWarning) output = [] for f in model._meta.local_many_to_many: if (model._meta.managed or f.rel.to._met...
'Return the CREATE TABLE statements for a single m2m field'
def sql_for_many_to_many_field(self, model, f, style):
import warnings warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', PendingDeprecationWarning) from django.db import models from django.db.backends.util import truncate_name output = [] if...
'Create the references to other tables required by a many-to-many table'
def sql_for_inline_many_to_many_references(self, model, field, style):
import warnings warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', PendingDeprecationWarning) from django.db import models opts = model._meta qn = self.connection.ops.quote_name table_out...
'Returns the CREATE INDEX SQL statements for a single model'
def sql_indexes_for_model(self, model, style):
if ((not model._meta.managed) or model._meta.proxy): return [] output = [] for f in model._meta.local_fields: output.extend(self.sql_indexes_for_field(model, f, style)) return output
'Return the CREATE INDEX SQL statements for a single model field'
def sql_indexes_for_field(self, model, f, style):
from django.db.backends.util import truncate_name if (f.db_index and (not f.unique)): qn = self.connection.ops.quote_name tablespace = (f.db_tablespace or model._meta.db_tablespace) if tablespace: sql = self.connection.ops.tablespace_sql(tablespace) if sql: ...
'Return the DROP TABLE and restraint dropping statements for a single model'
def sql_destroy_model(self, model, references_to_delete, style):
if ((not model._meta.managed) or model._meta.proxy): return [] qn = self.connection.ops.quote_name output = [('%s %s;' % (style.SQL_KEYWORD('DROP TABLE'), style.SQL_TABLE(qn(model._meta.db_table))))] if (model in references_to_delete): output.extend(self.sql_remove_table_constraint...
'Returns the DROP TABLE statements for a single m2m field'
def sql_destroy_many_to_many(self, model, f, style):
import warnings warnings.warn('Database creation API for m2m tables has been deprecated. M2M models are now automatically generated', PendingDeprecationWarning) qn = self.connection.ops.quote_name output = [] if f.auto_created: output.append(('%s ...
'Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created.'
def create_test_db(self, verbosity=1, autoclobber=False):
if (verbosity >= 1): print ("Creating test database '%s'..." % self.connection.alias) test_database_name = self._create_test_db(verbosity, autoclobber) self.connection.close() self.connection.settings_dict['NAME'] = test_database_name can_rollback = self._rollback_works() self.c...
'Internal implementation - creates the test db tables.'
def _create_test_db(self, verbosity, autoclobber):
suffix = self.sql_table_creation_suffix() if self.connection.settings_dict['TEST_NAME']: test_database_name = self.connection.settings_dict['TEST_NAME'] else: test_database_name = (TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']) qn = self.connection.ops.quote_name curso...
'Destroy a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created.'
def destroy_test_db(self, old_database_name, verbosity=1):
if (verbosity >= 1): print ("Destroying test database '%s'..." % self.connection.alias) self.connection.close() test_database_name = self.connection.settings_dict['NAME'] self.connection.settings_dict['NAME'] = old_database_name self._destroy_test_db(test_database_name, verbosity)
'Internal implementation - remove the test db tables.'
def _destroy_test_db(self, test_database_name, verbosity):
cursor = self.connection.cursor() self.set_autocommit() time.sleep(1) cursor.execute(('DROP DATABASE %s' % self.connection.ops.quote_name(test_database_name))) self.connection.close()
'Make sure a connection is in autocommit mode.'
def set_autocommit(self):
if hasattr(self.connection.connection, 'autocommit'): if callable(self.connection.connection.autocommit): self.connection.connection.autocommit(True) else: self.connection.connection.autocommit = True elif hasattr(self.connection.connection, 'set_isolation_level'): ...
'SQL to append to the end of the test table creation statements'
def sql_table_creation_suffix(self):
return ''
'Returns a tuple with elements of self.connection.settings_dict (a DATABASES setting value) that uniquely identify a database accordingly to the RDBMS particularities.'
def test_db_signature(self):
settings_dict = self.connection.settings_dict return (settings_dict['HOST'], settings_dict['PORT'], settings_dict['ENGINE'], settings_dict['NAME'])
'Puts the defaults into the settings dictionary for a given connection where no settings is provided.'
def ensure_defaults(self, alias):
try: conn = self.databases[alias] except KeyError: raise ConnectionDoesNotExist(("The connection %s doesn't exist" % alias)) conn.setdefault('ENGINE', 'django.db.backends.dummy') if ((conn['ENGINE'] == 'django.db.backends.') or (not conn['ENGINE'])): conn['ENGINE'] = ...
'Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW'
def process_request(self, request):
if ('HTTP_USER_AGENT' in request.META): 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 = request.get_host() old_url = [host, request.path] ...
'Send broken link emails and calculate the Etag, if needed.'
def process_response(self, request, response):
if (response.status_code == 404): if (settings.SEND_BROKEN_LINK_EMAILS and (not settings.DEBUG)): domain = request.get_host() referer = request.META.get('HTTP_REFERER', None) is_internal = _is_internal_request(domain, referer) path = request.get_full_path() ...
'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_active and request.user.is_staff))): response = http.HttpResponse() response['X-View'] = ('%s.%s' % (view_func.__module__, view_func.__name__)) return response
'Sets the cache, if needed.'
def process_response(self, request, response):
if (not self._should_update_cache(request, response)): return response if (request.method != 'GET'): return response if (not (response.status_code == 200)): return response timeout = get_max_age(response) if (timeout == None): timeout = self.cache_timeout elif (ti...
'Checks whether the page is already cached and returns the cached version if available.'
def process_request(self, request):
if ((not (request.method in ('GET', 'HEAD'))) or request.GET): request._cache_update_cache = False return None cache_key = get_cache_key(request, self.key_prefix) if (cache_key is None): request._cache_update_cache = True return None response = cache.get(cache_key, None) ...
'Return HTML code for traceback.'
def get_traceback_html(self):
if 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_module(loader.__modul...
'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
'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
'Validate 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 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.')
'Returns the ManagementForm instance for this FormSet.'
def _management_form(self):
if (self.data or self.files): 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=sel...
'Returns the total number of forms in this FormSet.'
def total_form_count(self):
if (self.data or self.files): 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_...
'Returns the number of forms that are required in this FormSet.'
def initial_form_count(self):
if (self.data or self.files): 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.data or self.files): defaults['data'] = self.data defaults['files'] = self.files if self.initial: try: defaults['initial'] = self.initial[i] except IndexError: pass if (i >...
'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.forms]) 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)
'Outputs a <ul> for this set of radio fields.'
def render(self):
return mark_safe((u'<ul>\n%s\n</ul>' % u'\n'.join([(u'<li>%s</li>' % force_unicode(w)) for w in self])))
'Returns an instance of the renderer.'
def get_renderer(self, name, value, attrs=None, choices=()):
if (value is None): value = '' str_value = force_unicode(value) final_attrs = self.build_attrs(attrs) choices = list(chain(self.choices, choices)) return self.renderer(name, str_value, final_attrs, choices)
'Given a list of rendered widgets (as strings), returns a Unicode string representing the HTML for the whole lot. This hook allows you to format the HTML design of the widgets, if needed.'
def format_output(self, rendered_widgets):
return u''.join(rendered_widgets)
'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.')