desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Destroy a test database, prompting the user for confirmation if the
database already exists.'
| def destroy_test_db(self, old_database_name, verbosity=1):
| self.connection.close()
test_database_name = self.connection.settings_dict['NAME']
if (verbosity >= 1):
test_db_repr = ''
if (verbosity >= 2):
test_db_repr = (" ('%s')" % test_database_name)
print ("Destroying test database for alias '%s'%s..." % (self.c... |
'Internal implementation - remove the test db tables.'
| def _destroy_test_db(self, test_database_name, verbosity):
| cursor = self.connection.cursor()
self._prepare_for_test_db_ddl()
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. - Deprecated, not used
anymore by Django code. Kept for compatibility with user code that
might use it.'
| def set_autocommit(self):
| pass
|
'Internal implementation - Hook for tasks that should be performed
before the ``CREATE DATABASE``/``DROP DATABASE`` clauses used by
testing code to create/ destroy test databases. Needed e.g. in
PostgreSQL to rollback and close any active transaction.'
| def _prepare_for_test_db_ddl(self):
| pass
|
'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']):
logger.warning('Forbidden (User agent): %s', request.path, extra={'status_code': 403, 'request': request})
... |
'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()
... |
'Gets the value to set for the X_FRAME_OPTIONS header.
By default this uses the value from the X_FRAME_OPTIONS Django
settings. If not found in settings, defaults to \'SAMEORIGIN\'.
This method can be overridden if needed, allowing it to vary based on
the request or response.'
| def get_xframe_options_value(self, request, response):
| return getattr(settings, 'X_FRAME_OPTIONS', 'SAMEORIGIN').upper()
|
'Returns `True` if the `LocaleRegexURLResolver` is used
at root level of the urlpatterns, else it returns `False`.'
| def is_language_prefix_patterns_used(self):
| for url_pattern in get_resolver(None).url_patterns:
if isinstance(url_pattern, LocaleRegexURLResolver):
return True
return False
|
'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):
| assert hasattr(request, 'user'), "The XView middleware requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware'."
if ((request.method == 'HEAD') and ((request.META.get... |
'Sets the cache, if needed.'
| def process_response(self, request, response):
| if (not self._should_update_cache(request, response)):
return response
if (not (response.status_code == 200)):
return response
timeout = get_max_age(response)
if (timeout == None):
timeout = self.cache_timeout
elif (timeout == 0):
return response
patch_response_he... |
'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'))):
request._cache_update_cache = False
return None
cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
if (cache_key is None):
request._cache_update_cache = True
return None
response = self.cache.get(cach... |
'Class method to parse prefix node and return a Node.'
| @classmethod
def handle_token(cls, parser, token, name):
| tokens = token.contents.split()
if ((len(tokens) > 1) and (tokens[1] != 'as')):
raise template.TemplateSyntaxError(("First argument in '%s' must be 'as'" % tokens[0]))
if (len(tokens) > 1):
varname = tokens[2]
else:
varname = None
return cls(varname, name)
|
'Returns the object the view is displaying.
By default this requires `self.queryset` and a `pk` or `slug` argument
in the URLconf, but subclasses can override this to return any object.'
| def get_object(self, queryset=None):
| if (queryset is None):
queryset = self.get_queryset()
pk = self.kwargs.get(self.pk_url_kwarg, None)
slug = self.kwargs.get(self.slug_url_kwarg, None)
if (pk is not None):
queryset = queryset.filter(pk=pk)
elif (slug is not None):
slug_field = self.get_slug_field()
que... |
'Get the queryset to look an object up against. May not be called if
`get_object` is overridden.'
| def get_queryset(self):
| if (self.queryset is None):
if self.model:
return self.model._default_manager.all()
else:
raise ImproperlyConfigured((u'%(cls)s is missing a queryset. Define %(cls)s.model, %(cls)s.queryset, or override %(cls)s.get_object().' % {'cls': self.__cla... |
'Get the name of a slug field to be used to look up by slug.'
| def get_slug_field(self):
| return self.slug_field
|
'Get the name to use for the object.'
| def get_context_object_name(self, obj):
| if self.context_object_name:
return self.context_object_name
elif hasattr(obj, '_meta'):
return smart_str(obj._meta.object_name.lower())
else:
return None
|
'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(SingleObjectTemplateResponseMixin, self).get_template_names()
except ImproperlyConfigured:
names = []
if (self.object and self.template_name_field):
name = getattr(self.object, self.template_name_field, None)
if name:
names.insert(0, name)
i... |
'Constructor. Called in the URLconf; can contain helpful extra
keyword arguments, and other things.'
| def __init__(self, **kwargs):
| for (key, value) in kwargs.iteritems():
setattr(self, key, value)
|
'Main entry point for a request-response process.'
| @classonlymethod
def as_view(cls, **initkwargs):
| for key in initkwargs:
if (key in cls.http_method_names):
raise TypeError((u"You tried to pass in the %s method name as a keyword argument to %s(). Don't do that." % (key, cls.__name__)))
if (not hasattr(cls, key)):
raise Typ... |
'Returns a response with a template rendered with the given context.'
| def render_to_response(self, context, **response_kwargs):
| return self.response_class(request=self.request, template=self.get_template_names(), context=context, **response_kwargs)
|
'Returns 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):
| if (self.template_name is None):
raise ImproperlyConfigured("TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'")
else:
return [self.template_name]
|
'Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.'
| def get_redirect_url(self, **kwargs):
| if self.url:
url = (self.url % kwargs)
args = self.request.META.get('QUERY_STRING', '')
if (args and self.query_string):
url = ('%s?%s' % (url, args))
return url
else:
return None
|
'Get a year format string in strptime syntax to be used to parse the
year from url variables.'
| def get_year_format(self):
| return self.year_format
|
'Return the year for which this view should display data'
| def get_year(self):
| year = self.year
if (year is None):
try:
year = self.kwargs['year']
except KeyError:
try:
year = self.request.GET['year']
except KeyError:
raise Http404(_(u'No year specified'))
return year
|
'Get a month format string in strptime syntax to be used to parse the
month from url variables.'
| def get_month_format(self):
| return self.month_format
|
'Return the month for which this view should display data'
| def get_month(self):
| month = self.month
if (month is None):
try:
month = self.kwargs['month']
except KeyError:
try:
month = self.request.GET['month']
except KeyError:
raise Http404(_(u'No month specified'))
return month
|
'Get the next valid month.'
| def get_next_month(self, date):
| (first_day, last_day) = _month_bounds(date)
next = (last_day + datetime.timedelta(days=1)).replace(day=1)
return _get_next_prev_month(self, next, is_previous=False, use_first_day=True)
|
'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): timezone.now()})
if ((not allow_empty) and (not qs)):
raise ... |
'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 = (queryset or self.get_queryset())
if ((not self.get_allow_future()) and (date > datetime.date.today())):
... |
'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.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 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
|
'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, 'sensitive_post_parameters', [])
if (self.is_active(request) and sensitive_post_parameters):
cleansed = request.POST.copy()
if (sensitive_post_parameters == '__ALL__'):
... |
'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 == 'sensitive_variables_wrapper') and ('sensitive_variables_wrapper' in current_frame.f_locals)):
wrapper = current_frame.f_locals['sensitive_variables_wrapper'... |
'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 ... |
'Return HTML version of debug 500 HTTP error page.'
| def get_traceback_html(self):
| t = Template(TECHNICAL_500_TEMPLATE, name='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='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, '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
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 isin... |
'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)
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, '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 (isinstance(value, basestring) and (value.lower() 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.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.