2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2007-10-28 11:38:08 +08:00
|
|
|
Field classes.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
|
2013-07-30 01:19:04 +08:00
|
|
|
from __future__ import unicode_literals
|
2011-10-18 00:56:18 +08:00
|
|
|
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2007-05-17 05:20:35 +08:00
|
|
|
import datetime
|
2008-03-20 06:29:11 +08:00
|
|
|
import os
|
2007-05-17 05:20:35 +08:00
|
|
|
import re
|
2013-03-19 13:04:59 +08:00
|
|
|
import sys
|
2014-07-15 17:35:29 +08:00
|
|
|
import uuid
|
2013-09-28 16:22:46 +08:00
|
|
|
import warnings
|
2009-12-18 06:06:41 +08:00
|
|
|
from decimal import Decimal, DecimalException
|
2012-05-06 01:47:03 +08:00
|
|
|
from io import BytesIO
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
from django.core import validators
|
2011-10-18 00:56:18 +08:00
|
|
|
from django.core.exceptions import ValidationError
|
2015-01-28 20:35:27 +08:00
|
|
|
# Provide this import for backwards compatibility.
|
|
|
|
from django.core.validators import EMPTY_VALUES # NOQA
|
2013-11-30 03:38:13 +08:00
|
|
|
from django.forms.utils import from_current_timezone, to_current_timezone
|
2013-01-28 21:12:56 +08:00
|
|
|
from django.forms.widgets import (
|
2015-01-28 20:35:27 +08:00
|
|
|
FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput, DateInput,
|
|
|
|
DateTimeInput, EmailInput, HiddenInput, MultipleHiddenInput,
|
|
|
|
NullBooleanSelect, NumberInput, Select, SelectMultiple,
|
|
|
|
SplitDateTimeWidget, SplitHiddenDateTimeWidget, TextInput, TimeInput,
|
|
|
|
URLInput,
|
2013-01-28 21:12:56 +08:00
|
|
|
)
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils import formats, six
|
2014-07-24 20:57:24 +08:00
|
|
|
from django.utils.dateparse import parse_duration
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.deprecation import (
|
|
|
|
RemovedInDjango20Warning, RenameMethodsBase,
|
|
|
|
)
|
2014-07-24 20:57:24 +08:00
|
|
|
from django.utils.duration import duration_string
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.encoding import force_str, force_text, smart_text
|
|
|
|
from django.utils.ipv6 import clean_ipv6_address
|
2013-09-06 03:38:59 +08:00
|
|
|
from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
|
2013-01-31 04:29:39 +08:00
|
|
|
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
|
2007-05-17 05:20:35 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
__all__ = (
|
|
|
|
'Field', 'CharField', 'IntegerField',
|
2014-07-24 20:57:24 +08:00
|
|
|
'DateField', 'TimeField', 'DateTimeField', 'DurationField',
|
2007-10-28 11:38:08 +08:00
|
|
|
'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
|
|
|
|
'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
|
2007-05-21 09:29:58 +08:00
|
|
|
'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
|
2015-01-18 09:42:41 +08:00
|
|
|
'SplitDateTimeField', 'GenericIPAddressField', 'FilePathField',
|
2014-07-15 17:35:29 +08:00
|
|
|
'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField', 'UUIDField',
|
2006-10-29 04:34:37 +08:00
|
|
|
)
|
|
|
|
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
class RenameFieldMethods(RenameMethodsBase):
|
|
|
|
renamed_methods = (
|
|
|
|
('_has_changed', 'has_changed', RemovedInDjango20Warning),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class Field(six.with_metaclass(RenameFieldMethods, object)):
|
2013-11-03 03:27:47 +08:00
|
|
|
widget = TextInput # Default widget to use when rendering this type of Field.
|
|
|
|
hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
|
|
|
|
default_validators = [] # Default set of validators
|
2013-03-14 23:19:59 +08:00
|
|
|
# Add an 'invalid' entry to default_error_message if you want a specific
|
|
|
|
# field error message not raised by the field validators.
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'required': _('This field is required.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2013-03-07 16:21:59 +08:00
|
|
|
empty_values = list(validators.EMPTY_VALUES)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-11-24 01:40:33 +08:00
|
|
|
# Tracks each time a Field instance is created. Used to retain order.
|
|
|
|
creation_counter = 0
|
|
|
|
|
2007-10-28 13:40:26 +08:00
|
|
|
def __init__(self, required=True, widget=None, label=None, initial=None,
|
2013-03-26 04:25:53 +08:00
|
|
|
help_text='', error_messages=None, show_hidden_initial=False,
|
2014-04-29 16:07:57 +08:00
|
|
|
validators=[], localize=False, label_suffix=None):
|
2006-12-28 08:01:52 +08:00
|
|
|
# required -- Boolean that specifies whether the field is required.
|
|
|
|
# True by default.
|
2007-04-01 13:05:59 +08:00
|
|
|
# widget -- A Widget class, or instance of a Widget class, that should
|
|
|
|
# be used for this Field when displaying it. Each Field has a
|
|
|
|
# default Widget that it'll use if you don't specify this. In
|
|
|
|
# most cases, the default widget is TextInput.
|
|
|
|
# label -- A verbose name for this field, for use in displaying this
|
|
|
|
# field in a form. By default, Django will use a "pretty"
|
|
|
|
# version of the form field name, if the Field is part of a
|
|
|
|
# Form.
|
|
|
|
# initial -- A value to use in this Field's initial display. This value
|
|
|
|
# is *not* used as a fallback if data isn't given.
|
2007-01-29 06:10:04 +08:00
|
|
|
# help_text -- An optional string to use as "help text" for this Field.
|
2010-03-28 00:43:27 +08:00
|
|
|
# error_messages -- An optional dictionary to override the default
|
|
|
|
# messages that the field will raise.
|
2008-09-02 05:28:32 +08:00
|
|
|
# show_hidden_initial -- Boolean that specifies if it is needed to render a
|
|
|
|
# hidden widget with initial value after widget.
|
2014-05-29 08:39:14 +08:00
|
|
|
# validators -- List of additional validators to use
|
2010-03-28 00:43:27 +08:00
|
|
|
# localize -- Boolean that specifies if the field should be localized.
|
2014-04-29 16:07:57 +08:00
|
|
|
# label_suffix -- Suffix to be added to the label. Overrides
|
|
|
|
# form's label_suffix.
|
2006-12-28 08:01:52 +08:00
|
|
|
self.required, self.label, self.initial = required, label, initial
|
2008-09-02 05:28:32 +08:00
|
|
|
self.show_hidden_initial = show_hidden_initial
|
2013-03-26 04:25:53 +08:00
|
|
|
self.help_text = help_text
|
2014-04-29 16:07:57 +08:00
|
|
|
self.label_suffix = label_suffix
|
2006-10-29 04:34:37 +08:00
|
|
|
widget = widget or self.widget
|
|
|
|
if isinstance(widget, type):
|
|
|
|
widget = widget()
|
2006-12-09 02:54:53 +08:00
|
|
|
|
2010-03-28 00:43:27 +08:00
|
|
|
# Trigger the localization machinery if needed.
|
|
|
|
self.localize = localize
|
2010-05-21 22:07:54 +08:00
|
|
|
if self.localize:
|
|
|
|
widget.is_localized = True
|
2010-03-28 00:43:27 +08:00
|
|
|
|
2010-10-01 10:02:58 +08:00
|
|
|
# Let the widget know whether it should display as required.
|
|
|
|
widget.is_required = self.required
|
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
# Hook into self.widget_attrs() for any Field-specific HTML attributes.
|
|
|
|
extra_attrs = self.widget_attrs(widget)
|
|
|
|
if extra_attrs:
|
|
|
|
widget.attrs.update(extra_attrs)
|
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
self.widget = widget
|
|
|
|
|
2006-11-24 01:40:33 +08:00
|
|
|
# Increase the creation counter, and save our local copy.
|
|
|
|
self.creation_counter = Field.creation_counter
|
|
|
|
Field.creation_counter += 1
|
|
|
|
|
2007-12-02 00:50:48 +08:00
|
|
|
messages = {}
|
2010-01-05 11:56:19 +08:00
|
|
|
for c in reversed(self.__class__.__mro__):
|
|
|
|
messages.update(getattr(c, 'default_error_messages', {}))
|
2007-12-02 00:50:48 +08:00
|
|
|
messages.update(error_messages or {})
|
|
|
|
self.error_messages = messages
|
2007-10-28 13:40:26 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
self.validators = self.default_validators + validators
|
2013-03-19 05:22:26 +08:00
|
|
|
super(Field, self).__init__()
|
2010-01-05 11:56:19 +08:00
|
|
|
|
2010-08-14 20:05:41 +08:00
|
|
|
def prepare_value(self, value):
|
|
|
|
return value
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
return value
|
|
|
|
|
|
|
|
def validate(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values and self.required:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def run_validators(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
return
|
|
|
|
errors = []
|
|
|
|
for v in self.validators:
|
|
|
|
try:
|
|
|
|
v(value)
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2010-01-05 11:56:19 +08:00
|
|
|
if hasattr(e, 'code') and e.code in self.error_messages:
|
2013-04-05 03:21:57 +08:00
|
|
|
e.message = self.error_messages[e.code]
|
|
|
|
errors.extend(e.error_list)
|
2010-01-05 11:56:19 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
def clean(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2006-11-05 04:49:59 +08:00
|
|
|
Validates the given value and returns its "cleaned" value as an
|
2006-10-29 04:34:37 +08:00
|
|
|
appropriate Python object.
|
|
|
|
|
|
|
|
Raises ValidationError for any errors.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = self.to_python(value)
|
|
|
|
self.validate(value)
|
|
|
|
self.run_validators(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
return value
|
|
|
|
|
2010-10-01 10:02:58 +08:00
|
|
|
def bound_data(self, data, initial):
|
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
return data
|
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
return {}
|
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
"""
|
|
|
|
Return True if data differs from initial.
|
|
|
|
"""
|
|
|
|
# For purposes of seeing whether something has changed, None is
|
2014-04-27 01:18:45 +08:00
|
|
|
# the same as an empty string, if the data or initial value we get
|
2013-01-26 03:50:46 +08:00
|
|
|
# is None, replace it w/ ''.
|
2013-01-27 00:05:47 +08:00
|
|
|
initial_value = initial if initial is not None else ''
|
|
|
|
try:
|
|
|
|
data = self.to_python(data)
|
2014-02-20 20:40:42 +08:00
|
|
|
if hasattr(self, '_coerce'):
|
|
|
|
data = self._coerce(data)
|
2013-01-27 00:05:47 +08:00
|
|
|
except ValidationError:
|
2013-01-26 03:50:46 +08:00
|
|
|
return True
|
2013-01-27 00:05:47 +08:00
|
|
|
data_value = data if data is not None else ''
|
|
|
|
return initial_value != data_value
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2007-09-14 11:29:39 +08:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = copy.copy(self)
|
|
|
|
memo[id(self)] = result
|
|
|
|
result.widget = copy.deepcopy(self.widget, memo)
|
2011-10-28 22:38:41 +08:00
|
|
|
result.validators = self.validators[:]
|
2007-09-14 11:29:39 +08:00
|
|
|
return result
|
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class CharField(Field):
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, max_length=None, min_length=None, *args, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
self.max_length, self.min_length = max_length, min_length
|
2007-01-29 06:10:04 +08:00
|
|
|
super(CharField, self).__init__(*args, **kwargs)
|
2010-01-05 11:56:19 +08:00
|
|
|
if min_length is not None:
|
2013-05-18 19:26:07 +08:00
|
|
|
self.validators.append(validators.MinLengthValidator(int(min_length)))
|
2010-01-05 11:56:19 +08:00
|
|
|
if max_length is not None:
|
2013-05-18 19:26:07 +08:00
|
|
|
self.validators.append(validators.MaxLengthValidator(int(max_length)))
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
"Returns a Unicode object."
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
2011-11-15 17:36:08 +08:00
|
|
|
attrs = super(CharField, self).widget_attrs(widget)
|
2014-03-04 22:12:13 +08:00
|
|
|
if self.max_length is not None:
|
2007-08-05 13:14:46 +08:00
|
|
|
# The HTML attribute is maxlength, not max_length.
|
2011-11-15 17:36:08 +08:00
|
|
|
attrs.update({'maxlength': str(self.max_length)})
|
|
|
|
return attrs
|
2006-12-09 02:54:53 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class IntegerField(Field):
|
2014-03-13 23:55:38 +08:00
|
|
|
widget = NumberInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a whole number.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, max_value=None, min_value=None, *args, **kwargs):
|
2011-01-14 00:41:46 +08:00
|
|
|
self.max_value, self.min_value = max_value, min_value
|
2014-03-13 23:55:38 +08:00
|
|
|
if kwargs.get('localize') and self.widget == NumberInput:
|
|
|
|
# Localized number input is not well supported on most browsers
|
|
|
|
kwargs.setdefault('widget', super(IntegerField, self).widget)
|
2007-01-29 06:10:04 +08:00
|
|
|
super(IntegerField, self).__init__(*args, **kwargs)
|
2006-12-16 07:18:47 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
if max_value is not None:
|
|
|
|
self.validators.append(validators.MaxValueValidator(max_value))
|
|
|
|
if min_value is not None:
|
|
|
|
self.validators.append(validators.MinValueValidator(min_value))
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that int() can be called on the input. Returns the result
|
2007-01-13 13:08:07 +08:00
|
|
|
of int(). Returns None for empty values.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(IntegerField, self).to_python(value)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2007-01-13 13:08:07 +08:00
|
|
|
return None
|
2010-03-28 00:43:27 +08:00
|
|
|
if self.localize:
|
|
|
|
value = formats.sanitize_separators(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
2007-09-15 19:45:19 +08:00
|
|
|
value = int(str(value))
|
2006-10-29 04:34:37 +08:00
|
|
|
except (ValueError, TypeError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2006-12-16 07:18:47 +08:00
|
|
|
return value
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super(IntegerField, self).widget_attrs(widget)
|
|
|
|
if isinstance(widget, NumberInput):
|
|
|
|
if self.min_value is not None:
|
|
|
|
attrs['min'] = self.min_value
|
|
|
|
if self.max_value is not None:
|
|
|
|
attrs['max'] = self.max_value
|
|
|
|
return attrs
|
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class FloatField(IntegerField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a number.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
Validates that float() can be called on the input. Returns the result
|
|
|
|
of float(). Returns None for empty values.
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
value = super(IntegerField, self).to_python(value)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2007-05-21 09:29:58 +08:00
|
|
|
return None
|
2010-03-28 00:43:27 +08:00
|
|
|
if self.localize:
|
|
|
|
value = formats.sanitize_separators(value)
|
2007-05-21 09:29:58 +08:00
|
|
|
try:
|
2010-03-01 18:19:24 +08:00
|
|
|
value = float(value)
|
2007-05-21 09:29:58 +08:00
|
|
|
except (ValueError, TypeError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2007-05-21 09:29:58 +08:00
|
|
|
return value
|
|
|
|
|
2013-09-07 00:54:48 +08:00
|
|
|
def validate(self, value):
|
|
|
|
super(FloatField, self).validate(value)
|
|
|
|
|
|
|
|
# Check for NaN (which is the only thing not equal to itself) and +/- infinity
|
|
|
|
if value != value or value in (Decimal('Inf'), Decimal('-Inf')):
|
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
|
|
|
|
|
|
|
return value
|
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super(FloatField, self).widget_attrs(widget)
|
2014-01-11 21:05:28 +08:00
|
|
|
if isinstance(widget, NumberInput) and 'step' not in widget.attrs:
|
2013-02-23 16:45:56 +08:00
|
|
|
attrs.setdefault('step', 'any')
|
|
|
|
return attrs
|
|
|
|
|
|
|
|
|
|
|
|
class DecimalField(IntegerField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a number.'),
|
2013-04-14 00:20:01 +08:00
|
|
|
'max_digits': ungettext_lazy(
|
|
|
|
'Ensure that there are no more than %(max)s digit in total.',
|
|
|
|
'Ensure that there are no more than %(max)s digits in total.',
|
|
|
|
'max'),
|
|
|
|
'max_decimal_places': ungettext_lazy(
|
|
|
|
'Ensure that there are no more than %(max)s decimal place.',
|
|
|
|
'Ensure that there are no more than %(max)s decimal places.',
|
|
|
|
'max'),
|
|
|
|
'max_whole_digits': ungettext_lazy(
|
|
|
|
'Ensure that there are no more than %(max)s digit before the decimal point.',
|
|
|
|
'Ensure that there are no more than %(max)s digits before the decimal point.',
|
|
|
|
'max'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-05-21 09:29:58 +08:00
|
|
|
def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
|
|
|
|
self.max_digits, self.decimal_places = max_digits, decimal_places
|
2013-02-23 16:45:56 +08:00
|
|
|
super(DecimalField, self).__init__(max_value, min_value, *args, **kwargs)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2007-05-21 09:29:58 +08:00
|
|
|
return None
|
2010-03-28 00:43:27 +08:00
|
|
|
if self.localize:
|
|
|
|
value = formats.sanitize_separators(value)
|
2012-07-21 16:00:10 +08:00
|
|
|
value = smart_text(value).strip()
|
2007-07-13 17:09:59 +08:00
|
|
|
try:
|
2010-03-01 18:19:24 +08:00
|
|
|
value = Decimal(value)
|
2007-07-13 17:09:59 +08:00
|
|
|
except DecimalException:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2010-01-05 11:56:19 +08:00
|
|
|
return value
|
2008-08-16 04:09:47 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
super(DecimalField, self).validate(value)
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2010-01-05 11:56:19 +08:00
|
|
|
return
|
2010-02-22 22:38:44 +08:00
|
|
|
# Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
|
|
|
|
# since it is never equal to itself. However, NaN is the only value that
|
|
|
|
# isn't equal to itself, so we can use this to identify NaN
|
|
|
|
if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2008-08-16 04:09:47 +08:00
|
|
|
sign, digittuple, exponent = value.as_tuple()
|
|
|
|
decimals = abs(exponent)
|
|
|
|
# digittuple doesn't include any leading zeros.
|
|
|
|
digits = len(digittuple)
|
2008-11-11 03:52:53 +08:00
|
|
|
if decimals > digits:
|
2008-08-16 04:09:47 +08:00
|
|
|
# We have leading zeros up to or past the decimal point. Count
|
2009-04-16 22:24:27 +08:00
|
|
|
# everything past the decimal point as a digit. We do not count
|
|
|
|
# 0 before the decimal point as a digit since that would mean
|
2008-11-11 03:52:53 +08:00
|
|
|
# we would not allow max_digits = decimal_places.
|
|
|
|
digits = decimals
|
2008-08-16 04:09:47 +08:00
|
|
|
whole_digits = digits - decimals
|
|
|
|
|
|
|
|
if self.max_digits is not None and digits > self.max_digits:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['max_digits'],
|
|
|
|
code='max_digits',
|
|
|
|
params={'max': self.max_digits},
|
|
|
|
)
|
2007-05-21 09:29:58 +08:00
|
|
|
if self.decimal_places is not None and decimals > self.decimal_places:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['max_decimal_places'],
|
|
|
|
code='max_decimal_places',
|
|
|
|
params={'max': self.decimal_places},
|
|
|
|
)
|
2013-04-14 00:20:01 +08:00
|
|
|
if (self.max_digits is not None and self.decimal_places is not None
|
|
|
|
and whole_digits > (self.max_digits - self.decimal_places)):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['max_whole_digits'],
|
|
|
|
code='max_whole_digits',
|
|
|
|
params={'max': (self.max_digits - self.decimal_places)},
|
|
|
|
)
|
2007-05-21 09:29:58 +08:00
|
|
|
return value
|
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super(DecimalField, self).widget_attrs(widget)
|
2014-01-11 21:05:28 +08:00
|
|
|
if isinstance(widget, NumberInput) and 'step' not in widget.attrs:
|
2013-07-19 10:01:51 +08:00
|
|
|
if self.decimal_places is not None:
|
|
|
|
# Use exponential notation for small values since they might
|
|
|
|
# be parsed as 0 otherwise. ref #20765
|
|
|
|
step = str(Decimal('1') / 10 ** self.decimal_places).lower()
|
|
|
|
else:
|
|
|
|
step = 'any'
|
|
|
|
attrs.setdefault('step', step)
|
2013-02-23 16:45:56 +08:00
|
|
|
return attrs
|
|
|
|
|
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class BaseTemporalField(Field):
|
|
|
|
|
|
|
|
def __init__(self, input_formats=None, *args, **kwargs):
|
|
|
|
super(BaseTemporalField, self).__init__(*args, **kwargs)
|
|
|
|
if input_formats is not None:
|
|
|
|
self.input_formats = input_formats
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
# Try to coerce the value to unicode.
|
2012-07-21 16:00:10 +08:00
|
|
|
unicode_value = force_text(value, strings_only=True)
|
2012-07-20 20:48:51 +08:00
|
|
|
if isinstance(unicode_value, six.text_type):
|
2011-05-02 00:14:57 +08:00
|
|
|
value = unicode_value.strip()
|
|
|
|
# If unicode, try to strptime against each input format.
|
2012-07-20 20:48:51 +08:00
|
|
|
if isinstance(value, six.text_type):
|
2011-05-02 00:14:57 +08:00
|
|
|
for format in self.input_formats:
|
|
|
|
try:
|
|
|
|
return self.strptime(value, format)
|
2012-09-23 19:25:47 +08:00
|
|
|
except (ValueError, TypeError):
|
2012-04-05 22:49:02 +08:00
|
|
|
continue
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2011-05-02 00:14:57 +08:00
|
|
|
|
|
|
|
def strptime(self, value, format):
|
|
|
|
raise NotImplementedError('Subclasses must define this method.')
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class DateField(BaseTemporalField):
|
2009-04-16 22:24:27 +08:00
|
|
|
widget = DateInput
|
2011-05-02 00:14:57 +08:00
|
|
|
input_formats = formats.get_format_lazy('DATE_INPUT_FORMATS')
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid date.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a date. Returns a Python
|
|
|
|
datetime.date object.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2006-10-29 04:34:37 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
return value.date()
|
|
|
|
if isinstance(value, datetime.date):
|
|
|
|
return value
|
2011-05-02 00:14:57 +08:00
|
|
|
return super(DateField, self).to_python(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
def strptime(self, value, format):
|
2013-01-27 03:49:02 +08:00
|
|
|
return datetime.datetime.strptime(force_str(value), format).date()
|
2011-05-02 00:14:57 +08:00
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class TimeField(BaseTemporalField):
|
2008-08-24 01:36:42 +08:00
|
|
|
widget = TimeInput
|
2011-05-02 00:14:57 +08:00
|
|
|
input_formats = formats.get_format_lazy('TIME_INPUT_FORMATS')
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid time.')
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2006-12-15 04:35:32 +08:00
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a time. Returns a Python
|
|
|
|
datetime.time object.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2006-12-15 04:35:32 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.time):
|
|
|
|
return value
|
2011-05-02 00:14:57 +08:00
|
|
|
return super(TimeField, self).to_python(value)
|
|
|
|
|
|
|
|
def strptime(self, value, format):
|
2013-01-27 03:49:02 +08:00
|
|
|
return datetime.datetime.strptime(force_str(value), format).time()
|
2006-12-15 04:35:32 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class DateTimeField(BaseTemporalField):
|
2007-10-21 22:50:47 +08:00
|
|
|
widget = DateTimeInput
|
2011-05-02 00:14:57 +08:00
|
|
|
input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS')
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid date/time.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2007-10-21 22:50:47 +08:00
|
|
|
|
2011-11-18 21:01:06 +08:00
|
|
|
def prepare_value(self, value):
|
|
|
|
if isinstance(value, datetime.datetime):
|
|
|
|
value = to_current_timezone(value)
|
|
|
|
return value
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
Validates that the input can be converted to a datetime. Returns a
|
|
|
|
Python datetime.datetime object.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2006-10-29 04:34:37 +08:00
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.datetime):
|
2011-11-18 21:01:06 +08:00
|
|
|
return from_current_timezone(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
if isinstance(value, datetime.date):
|
2011-11-18 21:01:06 +08:00
|
|
|
result = datetime.datetime(value.year, value.month, value.day)
|
|
|
|
return from_current_timezone(result)
|
|
|
|
result = super(DateTimeField, self).to_python(value)
|
|
|
|
return from_current_timezone(result)
|
2011-05-02 00:14:57 +08:00
|
|
|
|
|
|
|
def strptime(self, value, format):
|
2013-01-27 03:49:02 +08:00
|
|
|
return datetime.datetime.strptime(force_str(value), format)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2014-07-24 20:57:24 +08:00
|
|
|
class DurationField(Field):
|
|
|
|
default_error_messages = {
|
|
|
|
'invalid': _('Enter a valid duration.'),
|
|
|
|
}
|
|
|
|
|
|
|
|
def prepare_value(self, value):
|
2015-02-14 06:12:23 +08:00
|
|
|
if isinstance(value, datetime.timedelta):
|
|
|
|
return duration_string(value)
|
2015-02-15 05:33:09 +08:00
|
|
|
return value
|
2014-07-24 20:57:24 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if value in self.empty_values:
|
|
|
|
return None
|
|
|
|
if isinstance(value, datetime.timedelta):
|
|
|
|
return value
|
|
|
|
value = parse_duration(value)
|
|
|
|
if value is None:
|
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
2007-07-13 20:03:20 +08:00
|
|
|
class RegexField(CharField):
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
2007-10-28 13:40:26 +08:00
|
|
|
# error_message is just kept for backwards compatibility:
|
2014-06-21 17:17:10 +08:00
|
|
|
if error_message is not None:
|
2014-08-03 06:33:18 +08:00
|
|
|
warnings.warn(
|
|
|
|
"The 'error_message' argument is deprecated. Use "
|
|
|
|
"Field.error_messages['invalid'] instead.",
|
|
|
|
RemovedInDjango20Warning, stacklevel=2
|
|
|
|
)
|
2007-10-28 13:40:26 +08:00
|
|
|
error_messages = kwargs.get('error_messages') or {}
|
|
|
|
error_messages['invalid'] = error_message
|
|
|
|
kwargs['error_messages'] = error_messages
|
2007-07-13 20:03:20 +08:00
|
|
|
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
|
2011-11-07 15:41:24 +08:00
|
|
|
self._set_regex(regex)
|
|
|
|
|
|
|
|
def _get_regex(self):
|
|
|
|
return self._regex
|
|
|
|
|
|
|
|
def _set_regex(self, regex):
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(regex, six.string_types):
|
2012-06-01 02:45:35 +08:00
|
|
|
regex = re.compile(regex, re.UNICODE)
|
2011-11-07 15:41:24 +08:00
|
|
|
self._regex = regex
|
|
|
|
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
|
|
|
|
self.validators.remove(self._regex_validator)
|
|
|
|
self._regex_validator = validators.RegexValidator(regex=regex)
|
|
|
|
self.validators.append(self._regex_validator)
|
|
|
|
|
|
|
|
regex = property(_get_regex, _set_regex)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class EmailField(CharField):
|
2013-01-28 21:12:56 +08:00
|
|
|
widget = EmailInput
|
2010-01-05 11:56:19 +08:00
|
|
|
default_validators = [validators.validate_email]
|
2007-08-06 21:58:56 +08:00
|
|
|
|
2010-10-07 23:50:36 +08:00
|
|
|
def clean(self, value):
|
|
|
|
value = self.to_python(value).strip()
|
|
|
|
return super(EmailField, self).clean(value)
|
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
class FileField(Field):
|
2010-10-01 10:02:58 +08:00
|
|
|
widget = ClearableFileInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _("No file was submitted. Check the encoding type on the form."),
|
|
|
|
'missing': _("No file was submitted."),
|
|
|
|
'empty': _("The submitted file is empty."),
|
2013-01-31 04:29:39 +08:00
|
|
|
'max_length': ungettext_lazy(
|
|
|
|
'Ensure this filename has at most %(max)d character (it has %(length)d).',
|
|
|
|
'Ensure this filename has at most %(max)d characters (it has %(length)d).',
|
|
|
|
'max'),
|
2012-06-08 00:08:47 +08:00
|
|
|
'contradiction': _('Please either submit a file or check the clear checkbox, not both.')
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
def __init__(self, *args, **kwargs):
|
2009-03-31 06:52:16 +08:00
|
|
|
self.max_length = kwargs.pop('max_length', None)
|
2011-04-23 05:18:27 +08:00
|
|
|
self.allow_empty_file = kwargs.pop('allow_empty_file', False)
|
2007-08-06 21:58:56 +08:00
|
|
|
super(FileField, self).__init__(*args, **kwargs)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, data):
|
2013-03-07 16:21:59 +08:00
|
|
|
if data in self.empty_values:
|
2007-08-06 21:58:56 +08:00
|
|
|
return None
|
2008-07-01 23:10:51 +08:00
|
|
|
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
# UploadedFile objects should have name and size attributes.
|
2007-08-06 21:58:56 +08:00
|
|
|
try:
|
2008-07-08 07:16:00 +08:00
|
|
|
file_name = data.name
|
|
|
|
file_size = data.size
|
2008-07-01 23:10:51 +08:00
|
|
|
except AttributeError:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2009-03-31 06:52:16 +08:00
|
|
|
if self.max_length is not None and len(file_name) > self.max_length:
|
2013-10-11 19:25:14 +08:00
|
|
|
params = {'max': self.max_length, 'length': len(file_name)}
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['max_length'], code='max_length', params=params)
|
2008-07-01 23:10:51 +08:00
|
|
|
if not file_name:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2011-04-23 05:18:27 +08:00
|
|
|
if not self.allow_empty_file and not file_size:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['empty'], code='empty')
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2008-07-08 07:16:00 +08:00
|
|
|
return data
|
2007-08-06 21:58:56 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def clean(self, data, initial=None):
|
2010-10-01 10:02:58 +08:00
|
|
|
# If the widget got contradictory inputs, we raise a validation error
|
|
|
|
if data is FILE_INPUT_CONTRADICTION:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['contradiction'], code='contradiction')
|
2010-10-01 10:02:58 +08:00
|
|
|
# False means the field value should be cleared; further validation is
|
|
|
|
# not needed.
|
|
|
|
if data is False:
|
|
|
|
if not self.required:
|
|
|
|
return False
|
|
|
|
# If the field is required, clearing is not possible (the widget
|
|
|
|
# shouldn't return False data in that case anyway). False is not
|
2013-03-07 16:21:59 +08:00
|
|
|
# in self.empty_value; if a False value makes it this far
|
2010-10-01 10:02:58 +08:00
|
|
|
# it should be validated from here on out as None (so it will be
|
|
|
|
# caught by the required check).
|
|
|
|
data = None
|
2010-01-05 11:56:19 +08:00
|
|
|
if not data and initial:
|
|
|
|
return initial
|
|
|
|
return super(FileField, self).clean(data)
|
|
|
|
|
2010-10-01 10:02:58 +08:00
|
|
|
def bound_data(self, data, initial):
|
|
|
|
if data in (None, FILE_INPUT_CONTRADICTION):
|
|
|
|
return initial
|
|
|
|
return data
|
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
if data is None:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
class ImageField(FileField):
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2014-09-04 20:15:09 +08:00
|
|
|
'invalid_image': _(
|
|
|
|
"Upload a valid image. The file you uploaded was either not an "
|
|
|
|
"image or a corrupted image."
|
|
|
|
),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, data):
|
2007-08-06 21:58:56 +08:00
|
|
|
"""
|
|
|
|
Checks that the file-upload field data contains a valid image (GIF, JPG,
|
|
|
|
PNG, possibly others -- whatever the Python Imaging Library supports).
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
f = super(ImageField, self).to_python(data)
|
2007-08-06 21:58:56 +08:00
|
|
|
if f is None:
|
|
|
|
return None
|
2010-02-22 22:38:44 +08:00
|
|
|
|
2014-03-21 22:54:53 +08:00
|
|
|
from PIL import Image
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2013-05-15 10:31:16 +08:00
|
|
|
# We need to get a file object for Pillow. We might have a path or we might
|
2008-07-01 23:10:51 +08:00
|
|
|
# have to read the data into memory.
|
|
|
|
if hasattr(data, 'temporary_file_path'):
|
|
|
|
file = data.temporary_file_path()
|
|
|
|
else:
|
|
|
|
if hasattr(data, 'read'):
|
2012-05-06 01:47:03 +08:00
|
|
|
file = BytesIO(data.read())
|
2008-07-01 23:10:51 +08:00
|
|
|
else:
|
2012-05-06 01:47:03 +08:00
|
|
|
file = BytesIO(data['content'])
|
2008-07-01 23:10:51 +08:00
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
try:
|
2012-07-31 03:57:22 +08:00
|
|
|
# load() could spot a truncated JPEG, but it loads the entire
|
|
|
|
# image in memory, which is a DoS vector. See #3848 and #18520.
|
2014-07-26 20:25:44 +08:00
|
|
|
image = Image.open(file)
|
2012-07-31 03:57:22 +08:00
|
|
|
# verify() must be called immediately after the constructor.
|
2014-07-26 20:25:44 +08:00
|
|
|
image.verify()
|
|
|
|
|
|
|
|
# Annotating so subclasses can reuse it for their own validation
|
|
|
|
f.image = image
|
|
|
|
f.content_type = Image.MIME[image.format]
|
2013-05-15 10:31:16 +08:00
|
|
|
except Exception:
|
2014-03-21 22:54:53 +08:00
|
|
|
# Pillow doesn't recognize it as an image.
|
2013-06-06 02:55:05 +08:00
|
|
|
six.reraise(ValidationError, ValidationError(
|
|
|
|
self.error_messages['invalid_image'],
|
|
|
|
code='invalid_image',
|
|
|
|
), sys.exc_info()[2])
|
2008-07-13 04:43:38 +08:00
|
|
|
if hasattr(f, 'seek') and callable(f.seek):
|
|
|
|
f.seek(0)
|
2007-08-06 21:58:56 +08:00
|
|
|
return f
|
2007-09-09 03:26:15 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class URLField(CharField):
|
2013-01-28 21:24:48 +08:00
|
|
|
widget = URLInput
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a valid URL.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2013-06-14 00:37:08 +08:00
|
|
|
default_validators = [validators.URLValidator()]
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2011-09-10 06:57:12 +08:00
|
|
|
|
|
|
|
def split_url(url):
|
|
|
|
"""
|
|
|
|
Returns a list of url parts via ``urlparse.urlsplit`` (or raises a
|
|
|
|
``ValidationError`` exception for certain).
|
|
|
|
"""
|
|
|
|
try:
|
2012-07-20 21:36:52 +08:00
|
|
|
return list(urlsplit(url))
|
2011-09-10 06:57:12 +08:00
|
|
|
except ValueError:
|
|
|
|
# urlparse.urlsplit can raise a ValueError with some
|
|
|
|
# misformatted URLs.
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2011-09-10 06:57:12 +08:00
|
|
|
|
2011-09-10 06:32:38 +08:00
|
|
|
value = super(URLField, self).to_python(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
if value:
|
2011-09-10 06:57:12 +08:00
|
|
|
url_fields = split_url(value)
|
2010-11-21 18:08:28 +08:00
|
|
|
if not url_fields[0]:
|
|
|
|
# If no URL scheme given, assume http://
|
|
|
|
url_fields[0] = 'http'
|
|
|
|
if not url_fields[1]:
|
|
|
|
# Assume that if no domain is provided, that the path segment
|
2011-01-14 00:41:46 +08:00
|
|
|
# contains the domain.
|
2010-11-21 18:08:28 +08:00
|
|
|
url_fields[1] = url_fields[2]
|
|
|
|
url_fields[2] = ''
|
|
|
|
# Rebuild the url_fields list, since the domain segment may now
|
|
|
|
# contain the path too.
|
2012-07-20 21:36:52 +08:00
|
|
|
url_fields = split_url(urlunsplit(url_fields))
|
|
|
|
value = urlunsplit(url_fields)
|
2011-09-10 06:32:38 +08:00
|
|
|
return value
|
2006-11-02 07:52:43 +08:00
|
|
|
|
2013-05-18 22:06:08 +08:00
|
|
|
def clean(self, value):
|
|
|
|
value = self.to_python(value).strip()
|
|
|
|
return super(URLField, self).clean(value)
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2006-10-29 04:34:37 +08:00
|
|
|
class BooleanField(Field):
|
|
|
|
widget = CheckboxInput
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2007-11-30 03:22:03 +08:00
|
|
|
"""Returns a Python boolean object."""
|
|
|
|
# Explicitly check for the string 'False', which is what a hidden field
|
2009-05-02 22:52:34 +08:00
|
|
|
# will submit for False. Also check for '0', since this is what
|
|
|
|
# RadioSelect will provide. Because bool("True") == bool('1') == True,
|
|
|
|
# we don't need to handle that explicitly.
|
2012-07-20 20:22:00 +08:00
|
|
|
if isinstance(value, six.string_types) and value.lower() in ('false', '0'):
|
2008-06-30 18:44:56 +08:00
|
|
|
value = False
|
|
|
|
else:
|
|
|
|
value = bool(value)
|
2013-01-26 23:39:20 +08:00
|
|
|
return super(BooleanField, self).to_python(value)
|
|
|
|
|
|
|
|
def validate(self, value):
|
2008-06-30 18:44:56 +08:00
|
|
|
if not value and self.required:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
# Sometimes data or initial could be None or '' which should be the
|
|
|
|
# same thing as False.
|
|
|
|
if initial == 'False':
|
|
|
|
# show_hidden_initial may have transformed False to 'False'
|
|
|
|
initial = False
|
|
|
|
return bool(initial) != bool(data)
|
|
|
|
|
|
|
|
|
2007-01-24 13:23:19 +08:00
|
|
|
class NullBooleanField(BooleanField):
|
|
|
|
"""
|
|
|
|
A field whose valid values are None, True and False. Invalid values are
|
|
|
|
cleaned to None.
|
|
|
|
"""
|
|
|
|
widget = NullBooleanSelect
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2008-08-28 23:06:18 +08:00
|
|
|
"""
|
|
|
|
Explicitly checks for the string 'True' and 'False', which is what a
|
2014-07-30 01:04:13 +08:00
|
|
|
hidden field will submit for True and False, for 'true' and 'false',
|
|
|
|
which are likely to be returned by JavaScript serializations of forms,
|
|
|
|
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
|
2008-08-28 23:06:18 +08:00
|
|
|
"""
|
2014-07-30 01:04:13 +08:00
|
|
|
if value in (True, 'True', 'true', '1'):
|
2008-08-28 23:06:18 +08:00
|
|
|
return True
|
2014-07-30 01:04:13 +08:00
|
|
|
elif value in (False, 'False', 'false', '0'):
|
2008-08-28 23:06:18 +08:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return None
|
2007-01-24 13:23:19 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
pass
|
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
# None (unknown) and False (No) are not the same
|
|
|
|
if initial is not None:
|
|
|
|
initial = bool(initial)
|
|
|
|
if data is not None:
|
|
|
|
data = bool(data)
|
|
|
|
return initial != data
|
|
|
|
|
|
|
|
|
2014-10-28 04:21:59 +08:00
|
|
|
class CallableChoiceIterator(object):
|
|
|
|
def __init__(self, choices_func):
|
|
|
|
self.choices_func = choices_func
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for e in self.choices_func():
|
|
|
|
yield e
|
|
|
|
|
|
|
|
|
2006-11-02 11:16:12 +08:00
|
|
|
class ChoiceField(Field):
|
2007-04-21 13:43:32 +08:00
|
|
|
widget = Select
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, choices=(), required=True, widget=None, label=None,
|
2013-03-26 04:25:53 +08:00
|
|
|
initial=None, help_text='', *args, **kwargs):
|
2010-02-22 22:38:44 +08:00
|
|
|
super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
|
2010-01-05 11:56:19 +08:00
|
|
|
initial=initial, help_text=help_text, *args, **kwargs)
|
2006-11-02 11:16:12 +08:00
|
|
|
self.choices = choices
|
|
|
|
|
2011-06-17 00:34:38 +08:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = super(ChoiceField, self).__deepcopy__(memo)
|
|
|
|
result._choices = copy.deepcopy(self._choices, memo)
|
|
|
|
return result
|
|
|
|
|
2007-01-21 09:29:01 +08:00
|
|
|
def _get_choices(self):
|
|
|
|
return self._choices
|
|
|
|
|
|
|
|
def _set_choices(self, value):
|
|
|
|
# Setting choices also sets the choices on the widget.
|
2007-02-20 11:05:09 +08:00
|
|
|
# choices can be any iterable, but we call list() on it because
|
|
|
|
# it will be consumed more than once.
|
2014-10-28 04:21:59 +08:00
|
|
|
if callable(value):
|
|
|
|
value = CallableChoiceIterator(value)
|
|
|
|
else:
|
|
|
|
value = list(value)
|
|
|
|
|
|
|
|
self._choices = self.widget.choices = value
|
2007-01-21 09:29:01 +08:00
|
|
|
|
|
|
|
choices = property(_get_choices, _set_choices)
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
"Returns a Unicode object."
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2012-07-21 16:00:10 +08:00
|
|
|
return smart_text(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def validate(self, value):
|
2006-11-02 11:16:12 +08:00
|
|
|
"""
|
|
|
|
Validates that the input is in self.choices.
|
|
|
|
"""
|
2010-01-05 11:56:19 +08:00
|
|
|
super(ChoiceField, self).validate(value)
|
|
|
|
if value and not self.valid_value(value):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_choice'],
|
|
|
|
code='invalid_choice',
|
|
|
|
params={'value': value},
|
|
|
|
)
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2008-07-19 15:53:02 +08:00
|
|
|
def valid_value(self, value):
|
|
|
|
"Check to see if the provided value is a valid choice"
|
2013-03-14 21:45:41 +08:00
|
|
|
text_value = force_text(value)
|
2008-07-19 15:53:02 +08:00
|
|
|
for k, v in self.choices:
|
2010-02-24 02:27:51 +08:00
|
|
|
if isinstance(v, (list, tuple)):
|
2008-07-19 15:53:02 +08:00
|
|
|
# This is an optgroup, so look inside the group for options
|
|
|
|
for k2, v2 in v:
|
2013-03-14 21:45:41 +08:00
|
|
|
if value == k2 or text_value == force_text(k2):
|
2008-07-19 15:53:02 +08:00
|
|
|
return True
|
|
|
|
else:
|
2013-03-14 21:45:41 +08:00
|
|
|
if value == k or text_value == force_text(k):
|
2008-07-19 15:53:02 +08:00
|
|
|
return True
|
|
|
|
return False
|
Fixed #7830 -- Removed all of the remaining, deprecated, non-oldforms features:
* Support for representing files as strings was removed. Use `django.core.files.base.ContentFile` instead.
* Support for representing uploaded files as dictionaries was removed. Use `django.core.files.uploadedfile.SimpleUploadedFile` instead.
* The `filename`, `file_name`, `file_size`, and `chuck` properties of `UploadedFile` were removed. Use the `name`, `name`, `size`, and `chunks` properties instead, respectively.
* The `get_FIELD_filename`, `get_FIELD_url`, `get_FIELD_size`, and `save_FIELD_file` methods for Models with `FileField` fields were removed. Instead, use the `path`, `url`, and `size` attributes and `save` method on the field itself, respectively.
* The `get_FIELD_width` and `get_FIELD_height` methods for Models with `ImageField` fields were removed. Use the `width` and `height` attributes on the field itself instead.
* The dispatcher `connect`, `disconnect`, `send`, and `sendExact` functions were removed. Use the signal object's own `connect`, `disconnect`, `send`, and `send` methods instead, respectively.
* The `form_for_model` and `form_for_instance` functions were removed. Use a `ModelForm` subclass instead.
* Support for importing `django.newforms` was removed. Use `django.forms` instead.
* Support for importing `django.utils.images` was removed. Use `django.core.files.images` instead.
* Support for the `follow` argument in the `create_object` and `update_object` generic views was removed. Use the `django.forms` package and the new `form_class` argument instead.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@8291 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2008-08-11 05:10:47 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2008-09-01 04:10:50 +08:00
|
|
|
class TypedChoiceField(ChoiceField):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.coerce = kwargs.pop('coerce', lambda val: val)
|
|
|
|
self.empty_value = kwargs.pop('empty_value', '')
|
|
|
|
super(TypedChoiceField, self).__init__(*args, **kwargs)
|
2008-10-24 15:14:30 +08:00
|
|
|
|
2013-11-19 01:24:56 +08:00
|
|
|
def _coerce(self, value):
|
2008-09-01 04:10:50 +08:00
|
|
|
"""
|
2013-11-19 01:24:56 +08:00
|
|
|
Validate that the value can be coerced to the right type (if not empty).
|
2008-09-01 04:10:50 +08:00
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value == self.empty_value or value in self.empty_values:
|
2008-09-01 04:10:50 +08:00
|
|
|
return self.empty_value
|
|
|
|
try:
|
|
|
|
value = self.coerce(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
except (ValueError, TypeError, ValidationError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_choice'],
|
|
|
|
code='invalid_choice',
|
|
|
|
params={'value': value},
|
|
|
|
)
|
2008-09-01 04:10:50 +08:00
|
|
|
return value
|
|
|
|
|
2013-11-19 01:24:56 +08:00
|
|
|
def clean(self, value):
|
|
|
|
value = super(TypedChoiceField, self).clean(value)
|
|
|
|
return self._coerce(value)
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2006-11-02 11:16:12 +08:00
|
|
|
class MultipleChoiceField(ChoiceField):
|
2007-01-09 13:12:25 +08:00
|
|
|
hidden_widget = MultipleHiddenInput
|
2007-04-21 13:43:32 +08:00
|
|
|
widget = SelectMultiple
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
|
|
|
|
'invalid_list': _('Enter a list of values.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
2006-11-02 11:16:12 +08:00
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
|
|
|
if not value:
|
|
|
|
return []
|
|
|
|
elif not isinstance(value, (list, tuple)):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_list'], code='invalid_list')
|
2012-07-21 16:00:10 +08:00
|
|
|
return [smart_text(val) for val in value]
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def validate(self, value):
|
2006-11-02 11:16:12 +08:00
|
|
|
"""
|
|
|
|
Validates that the input is a list or tuple.
|
|
|
|
"""
|
|
|
|
if self.required and not value:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
2006-11-02 11:16:12 +08:00
|
|
|
# Validate that each value in the value list is in self.choices.
|
2010-01-05 11:56:19 +08:00
|
|
|
for val in value:
|
2008-07-19 15:53:02 +08:00
|
|
|
if not self.valid_value(val):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_choice'],
|
|
|
|
code='invalid_choice',
|
|
|
|
params={'value': val},
|
|
|
|
)
|
2006-11-05 04:49:59 +08:00
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
if initial is None:
|
|
|
|
initial = []
|
|
|
|
if data is None:
|
|
|
|
data = []
|
|
|
|
if len(initial) != len(data):
|
|
|
|
return True
|
2013-08-30 07:20:00 +08:00
|
|
|
initial_set = set(force_text(value) for value in initial)
|
|
|
|
data_set = set(force_text(value) for value in data)
|
2013-01-26 03:50:46 +08:00
|
|
|
return data_set != initial_set
|
|
|
|
|
|
|
|
|
2010-12-05 12:47:19 +08:00
|
|
|
class TypedMultipleChoiceField(MultipleChoiceField):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.coerce = kwargs.pop('coerce', lambda val: val)
|
|
|
|
self.empty_value = kwargs.pop('empty_value', [])
|
|
|
|
super(TypedMultipleChoiceField, self).__init__(*args, **kwargs)
|
|
|
|
|
2013-11-19 01:24:56 +08:00
|
|
|
def _coerce(self, value):
|
2010-12-05 12:47:19 +08:00
|
|
|
"""
|
|
|
|
Validates that the values are in self.choices and can be coerced to the
|
|
|
|
right type.
|
|
|
|
"""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value == self.empty_value or value in self.empty_values:
|
2010-12-05 12:47:19 +08:00
|
|
|
return self.empty_value
|
|
|
|
new_value = []
|
|
|
|
for choice in value:
|
|
|
|
try:
|
|
|
|
new_value.append(self.coerce(choice))
|
|
|
|
except (ValueError, TypeError, ValidationError):
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid_choice'],
|
|
|
|
code='invalid_choice',
|
|
|
|
params={'value': choice},
|
|
|
|
)
|
2010-12-05 12:47:19 +08:00
|
|
|
return new_value
|
|
|
|
|
2013-11-19 01:24:56 +08:00
|
|
|
def clean(self, value):
|
|
|
|
value = super(TypedMultipleChoiceField, self).clean(value)
|
|
|
|
return self._coerce(value)
|
|
|
|
|
2010-12-05 12:47:19 +08:00
|
|
|
def validate(self, value):
|
2013-03-14 21:45:41 +08:00
|
|
|
if value != self.empty_value:
|
|
|
|
super(TypedMultipleChoiceField, self).validate(value)
|
|
|
|
elif self.required:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
2013-03-14 21:45:41 +08:00
|
|
|
|
2010-12-05 12:47:19 +08:00
|
|
|
|
2006-11-05 04:49:59 +08:00
|
|
|
class ComboField(Field):
|
2007-01-24 04:23:07 +08:00
|
|
|
"""
|
|
|
|
A Field whose clean() method calls multiple Field clean() methods.
|
|
|
|
"""
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, fields=(), *args, **kwargs):
|
|
|
|
super(ComboField, self).__init__(*args, **kwargs)
|
2006-11-27 08:49:26 +08:00
|
|
|
# Set 'required' to False on the individual fields, because the
|
|
|
|
# required validation will be handled by ComboField, not by those
|
|
|
|
# individual fields.
|
|
|
|
for f in fields:
|
|
|
|
f.required = False
|
2006-11-05 04:49:59 +08:00
|
|
|
self.fields = fields
|
|
|
|
|
|
|
|
def clean(self, value):
|
|
|
|
"""
|
|
|
|
Validates the given value against all of self.fields, which is a
|
|
|
|
list of Field instances.
|
|
|
|
"""
|
2007-01-21 01:25:42 +08:00
|
|
|
super(ComboField, self).clean(value)
|
2006-11-05 04:49:59 +08:00
|
|
|
for field in self.fields:
|
|
|
|
value = field.clean(value)
|
|
|
|
return value
|
2007-01-24 04:23:07 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2007-01-24 04:23:07 +08:00
|
|
|
class MultiValueField(Field):
|
|
|
|
"""
|
2007-07-01 12:24:20 +08:00
|
|
|
A Field that aggregates the logic of multiple Fields.
|
2007-09-09 03:26:15 +08:00
|
|
|
|
2007-07-01 12:24:20 +08:00
|
|
|
Its clean() method takes a "decompressed" list of values, which are then
|
|
|
|
cleaned into a single value according to self.fields. Each value in
|
2007-01-24 04:23:07 +08:00
|
|
|
this list is cleaned by the corresponding field -- the first value is
|
|
|
|
cleaned by the first field, the second value is cleaned by the second
|
|
|
|
field, etc. Once all fields are cleaned, the list of clean values is
|
|
|
|
"compressed" into a single value.
|
|
|
|
|
2007-07-01 12:24:20 +08:00
|
|
|
Subclasses should not have to implement clean(). Instead, they must
|
|
|
|
implement compress(), which takes a list of valid values and returns a
|
|
|
|
"compressed" version of those values -- a single value.
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
You'll probably want to use this with MultiWidget.
|
|
|
|
"""
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid': _('Enter a list of values.'),
|
2013-05-07 17:06:03 +08:00
|
|
|
'incomplete': _('Enter a complete value.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2007-01-29 06:10:04 +08:00
|
|
|
def __init__(self, fields=(), *args, **kwargs):
|
2013-05-07 17:06:03 +08:00
|
|
|
self.require_all_fields = kwargs.pop('require_all_fields', True)
|
2007-01-29 06:10:04 +08:00
|
|
|
super(MultiValueField, self).__init__(*args, **kwargs)
|
2007-01-24 04:23:07 +08:00
|
|
|
for f in fields:
|
2013-05-07 17:06:03 +08:00
|
|
|
f.error_messages.setdefault('incomplete',
|
|
|
|
self.error_messages['incomplete'])
|
|
|
|
if self.require_all_fields:
|
|
|
|
# Set 'required' to False on the individual fields, because the
|
|
|
|
# required validation will be handled by MultiValueField, not
|
|
|
|
# by those individual fields.
|
|
|
|
f.required = False
|
2007-01-24 04:23:07 +08:00
|
|
|
self.fields = fields
|
|
|
|
|
2013-09-11 01:56:49 +08:00
|
|
|
def __deepcopy__(self, memo):
|
|
|
|
result = super(MultiValueField, self).__deepcopy__(memo)
|
2014-12-07 05:00:09 +08:00
|
|
|
result.fields = tuple(x.__deepcopy__(memo) for x in self.fields)
|
2013-09-11 01:56:49 +08:00
|
|
|
return result
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def validate(self, value):
|
|
|
|
pass
|
|
|
|
|
2007-01-24 04:23:07 +08:00
|
|
|
def clean(self, 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]).
|
|
|
|
"""
|
|
|
|
clean_data = []
|
2013-11-30 03:38:13 +08:00
|
|
|
errors = []
|
2007-06-23 11:32:59 +08:00
|
|
|
if not value or isinstance(value, (list, tuple)):
|
2013-03-07 16:21:59 +08:00
|
|
|
if not value or not [v for v in value if v not in self.empty_values]:
|
2007-06-23 11:32:59 +08:00
|
|
|
if self.required:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
2007-06-23 11:32:59 +08:00
|
|
|
else:
|
|
|
|
return self.compress([])
|
|
|
|
else:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
2007-01-24 04:23:07 +08:00
|
|
|
for i, field in enumerate(self.fields):
|
|
|
|
try:
|
|
|
|
field_value = value[i]
|
2007-04-26 20:46:04 +08:00
|
|
|
except IndexError:
|
2007-01-24 04:23:07 +08:00
|
|
|
field_value = None
|
2013-05-07 17:06:03 +08:00
|
|
|
if field_value in self.empty_values:
|
|
|
|
if self.require_all_fields:
|
|
|
|
# Raise a 'required' error if the MultiValueField is
|
|
|
|
# required and any field is empty.
|
|
|
|
if self.required:
|
|
|
|
raise ValidationError(self.error_messages['required'], code='required')
|
|
|
|
elif field.required:
|
|
|
|
# Otherwise, add an 'incomplete' error to the list of
|
|
|
|
# collected errors and skip field cleaning, if a required
|
|
|
|
# field is empty.
|
|
|
|
if field.error_messages['incomplete'] not in errors:
|
|
|
|
errors.append(field.error_messages['incomplete'])
|
|
|
|
continue
|
2007-01-24 04:23:07 +08:00
|
|
|
try:
|
|
|
|
clean_data.append(field.clean(field_value))
|
2012-04-29 00:09:37 +08:00
|
|
|
except ValidationError as e:
|
2007-01-24 04:23:07 +08:00
|
|
|
# Collect all validation errors in a single list, which we'll
|
|
|
|
# raise at the end of clean(), rather than raising a single
|
2013-05-07 17:06:03 +08:00
|
|
|
# exception for the first error we encounter. Skip duplicates.
|
|
|
|
errors.extend(m for m in e.error_list if m not in errors)
|
2007-01-24 04:23:07 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
out = self.compress(clean_data)
|
|
|
|
self.validate(out)
|
2012-02-04 20:48:12 +08:00
|
|
|
self.run_validators(out)
|
2010-01-05 11:56:19 +08:00
|
|
|
return out
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
def compress(self, data_list):
|
|
|
|
"""
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError('Subclasses must implement this method.')
|
|
|
|
|
2014-08-07 10:56:23 +08:00
|
|
|
def has_changed(self, initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
if initial is None:
|
|
|
|
initial = ['' for x in range(0, len(data))]
|
|
|
|
else:
|
|
|
|
if not isinstance(initial, list):
|
|
|
|
initial = self.widget.decompress(initial)
|
|
|
|
for field, initial, data in zip(self.fields, initial, data):
|
2014-12-09 06:37:59 +08:00
|
|
|
try:
|
|
|
|
initial = field.to_python(initial)
|
|
|
|
except ValidationError:
|
|
|
|
return True
|
|
|
|
if field.has_changed(initial, data):
|
2013-01-26 03:50:46 +08:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
class FilePathField(ChoiceField):
|
2012-04-22 22:44:08 +08:00
|
|
|
def __init__(self, path, match=None, recursive=False, allow_files=True,
|
|
|
|
allow_folders=False, required=True, widget=None, label=None,
|
2013-03-26 04:25:53 +08:00
|
|
|
initial=None, help_text='', *args, **kwargs):
|
2008-03-20 06:29:11 +08:00
|
|
|
self.path, self.match, self.recursive = path, match, recursive
|
2012-04-22 22:44:08 +08:00
|
|
|
self.allow_files, self.allow_folders = allow_files, allow_folders
|
2008-03-20 06:29:11 +08:00
|
|
|
super(FilePathField, self).__init__(choices=(), required=required,
|
|
|
|
widget=widget, label=label, initial=initial, help_text=help_text,
|
|
|
|
*args, **kwargs)
|
2009-04-16 22:24:27 +08:00
|
|
|
|
2009-04-09 02:53:55 +08:00
|
|
|
if self.required:
|
|
|
|
self.choices = []
|
|
|
|
else:
|
|
|
|
self.choices = [("", "---------")]
|
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
if self.match is not None:
|
|
|
|
self.match_re = re.compile(self.match)
|
2009-04-09 02:53:55 +08:00
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
if recursive:
|
2010-12-02 08:49:15 +08:00
|
|
|
for root, dirs, files in sorted(os.walk(self.path)):
|
2012-04-22 22:44:08 +08:00
|
|
|
if self.allow_files:
|
|
|
|
for f in files:
|
|
|
|
if self.match is None or self.match_re.search(f):
|
|
|
|
f = os.path.join(root, f)
|
|
|
|
self.choices.append((f, f.replace(path, "", 1)))
|
|
|
|
if self.allow_folders:
|
|
|
|
for f in dirs:
|
2012-05-16 23:56:56 +08:00
|
|
|
if f == '__pycache__':
|
|
|
|
continue
|
2012-04-22 22:44:08 +08:00
|
|
|
if self.match is None or self.match_re.search(f):
|
|
|
|
f = os.path.join(root, f)
|
|
|
|
self.choices.append((f, f.replace(path, "", 1)))
|
2008-03-20 06:29:11 +08:00
|
|
|
else:
|
|
|
|
try:
|
2010-12-02 08:49:15 +08:00
|
|
|
for f in sorted(os.listdir(self.path)):
|
2012-05-16 23:56:56 +08:00
|
|
|
if f == '__pycache__':
|
|
|
|
continue
|
2008-03-20 06:29:11 +08:00
|
|
|
full_file = os.path.join(self.path, f)
|
2012-04-22 22:44:08 +08:00
|
|
|
if (((self.allow_files and os.path.isfile(full_file)) or
|
2013-11-26 17:43:46 +08:00
|
|
|
(self.allow_folders and os.path.isdir(full_file))) and
|
|
|
|
(self.match is None or self.match_re.search(f))):
|
2008-03-20 06:29:11 +08:00
|
|
|
self.choices.append((full_file, f))
|
|
|
|
except OSError:
|
|
|
|
pass
|
2009-04-09 02:53:55 +08:00
|
|
|
|
2008-03-20 06:29:11 +08:00
|
|
|
self.widget.choices = self.choices
|
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2007-01-24 04:23:07 +08:00
|
|
|
class SplitDateTimeField(MultiValueField):
|
2008-11-11 03:42:55 +08:00
|
|
|
widget = SplitDateTimeWidget
|
2008-09-02 05:28:32 +08:00
|
|
|
hidden_widget = SplitHiddenDateTimeWidget
|
2007-10-28 13:40:26 +08:00
|
|
|
default_error_messages = {
|
2012-06-08 00:08:47 +08:00
|
|
|
'invalid_date': _('Enter a valid date.'),
|
|
|
|
'invalid_time': _('Enter a valid time.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2009-03-23 00:13:06 +08:00
|
|
|
def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
|
2007-10-28 13:40:26 +08:00
|
|
|
errors = self.default_error_messages.copy()
|
|
|
|
if 'error_messages' in kwargs:
|
|
|
|
errors.update(kwargs['error_messages'])
|
2010-05-21 22:07:54 +08:00
|
|
|
localize = kwargs.get('localize', False)
|
2007-10-28 13:40:26 +08:00
|
|
|
fields = (
|
2010-05-21 22:07:54 +08:00
|
|
|
DateField(input_formats=input_date_formats,
|
|
|
|
error_messages={'invalid': errors['invalid_date']},
|
|
|
|
localize=localize),
|
|
|
|
TimeField(input_formats=input_time_formats,
|
|
|
|
error_messages={'invalid': errors['invalid_time']},
|
|
|
|
localize=localize),
|
2007-10-28 13:40:26 +08:00
|
|
|
)
|
2007-01-29 06:10:04 +08:00
|
|
|
super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
|
2007-01-24 04:23:07 +08:00
|
|
|
|
|
|
|
def compress(self, data_list):
|
|
|
|
if data_list:
|
2007-06-23 11:32:59 +08:00
|
|
|
# Raise a validation error if time or date is empty
|
|
|
|
# (possible if SplitDateTimeField has required=False).
|
2013-03-07 16:21:59 +08:00
|
|
|
if data_list[0] in self.empty_values:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
|
2013-03-07 16:21:59 +08:00
|
|
|
if data_list[1] in self.empty_values:
|
2013-06-06 02:55:05 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid_time'], code='invalid_time')
|
2011-11-18 21:01:06 +08:00
|
|
|
result = datetime.datetime.combine(*data_list)
|
|
|
|
return from_current_timezone(result)
|
2007-01-24 04:23:07 +08:00
|
|
|
return None
|
2007-09-16 19:38:32 +08:00
|
|
|
|
|
|
|
|
2011-06-11 21:48:24 +08:00
|
|
|
class GenericIPAddressField(CharField):
|
|
|
|
def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs):
|
|
|
|
self.unpack_ipv4 = unpack_ipv4
|
2013-03-14 23:19:59 +08:00
|
|
|
self.default_validators = validators.ip_address_validators(protocol, unpack_ipv4)[0]
|
2011-06-11 21:48:24 +08:00
|
|
|
super(GenericIPAddressField, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2013-02-24 01:42:53 +08:00
|
|
|
value = value.strip()
|
2011-06-11 21:48:24 +08:00
|
|
|
if value and ':' in value:
|
2013-03-14 23:19:59 +08:00
|
|
|
return clean_ipv6_address(value, self.unpack_ipv4)
|
2011-06-11 21:48:24 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
class SlugField(CharField):
|
|
|
|
default_validators = [validators.validate_slug]
|
2013-05-18 22:06:08 +08:00
|
|
|
|
|
|
|
def clean(self, value):
|
|
|
|
value = self.to_python(value).strip()
|
|
|
|
return super(SlugField, self).clean(value)
|
2014-07-15 17:35:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
class UUIDField(CharField):
|
|
|
|
default_error_messages = {
|
|
|
|
'invalid': _('Enter a valid UUID.'),
|
|
|
|
}
|
|
|
|
|
|
|
|
def prepare_value(self, value):
|
|
|
|
if isinstance(value, uuid.UUID):
|
|
|
|
return value.hex
|
|
|
|
return value
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
value = super(UUIDField, self).to_python(value)
|
|
|
|
if value in self.empty_values:
|
|
|
|
return None
|
|
|
|
if not isinstance(value, uuid.UUID):
|
|
|
|
try:
|
|
|
|
value = uuid.UUID(value)
|
|
|
|
except ValueError:
|
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
|
|
|
return value
|