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
|
|
|
"""
|
|
|
|
|
2011-03-28 10:11:19 +08:00
|
|
|
import copy
|
2007-05-17 05:20:35 +08:00
|
|
|
import datetime
|
2019-06-09 08:56:37 +08:00
|
|
|
import json
|
2017-08-10 08:41:39 +08:00
|
|
|
import math
|
2018-08-20 07:21:57 +08:00
|
|
|
import operator
|
2008-03-20 06:29:11 +08:00
|
|
|
import os
|
2007-05-17 05:20:35 +08:00
|
|
|
import re
|
2014-07-15 17:35:29 +08:00
|
|
|
import uuid
|
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
|
2017-01-07 19:11:46 +08:00
|
|
|
from urllib.parse import urlsplit, urlunsplit
|
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-09-09 21:09:59 +08:00
|
|
|
from django.forms.boundfield import BoundField
|
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,
|
2018-04-03 11:06:08 +08:00
|
|
|
DateTimeInput, EmailInput, FileInput, HiddenInput, MultipleHiddenInput,
|
2015-01-28 20:35:27 +08:00
|
|
|
NullBooleanSelect, NumberInput, Select, SelectMultiple,
|
2019-06-09 08:56:37 +08:00
|
|
|
SplitDateTimeWidget, SplitHiddenDateTimeWidget, Textarea, TextInput,
|
|
|
|
TimeInput, URLInput,
|
2013-01-28 21:12:56 +08:00
|
|
|
)
|
2017-01-08 03:13:29 +08:00
|
|
|
from django.utils import formats
|
2019-10-09 18:08:50 +08:00
|
|
|
from django.utils.dateparse import parse_datetime, parse_duration
|
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.ipv6 import clean_ipv6_address
|
2019-10-26 22:42:32 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy as _, ngettext_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',
|
2019-06-09 08:56:37 +08:00
|
|
|
'JSONField', 'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField',
|
|
|
|
'UUIDField',
|
2006-10-29 04:34:37 +08:00
|
|
|
)
|
|
|
|
|
2009-12-23 01:58:49 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Field:
|
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
|
|
|
|
2017-06-03 22:49:01 +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,
|
2016-09-16 17:14:15 +08:00
|
|
|
validators=(), localize=False, disabled=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.
|
2015-07-08 03:06:57 +08:00
|
|
|
# disabled -- Boolean that specifies whether the field is disabled, that
|
|
|
|
# is its widget is shown in the form but not editable.
|
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
|
2015-07-08 03:06:57 +08:00
|
|
|
self.disabled = disabled
|
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()
|
2016-11-06 14:16:56 +08:00
|
|
|
else:
|
|
|
|
widget = copy.deepcopy(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
|
|
|
|
|
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
|
|
|
|
2017-12-11 20:08:45 +08:00
|
|
|
self.validators = [*self.default_validators, *validators]
|
2016-04-22 08:18:43 +08:00
|
|
|
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate the given value and return its "cleaned" value as an
|
|
|
|
appropriate Python object. Raise ValidationError for any errors.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
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.
|
|
|
|
"""
|
2016-01-29 02:49:51 +08:00
|
|
|
if self.disabled:
|
|
|
|
return initial
|
2010-10-01 10:02:58 +08:00
|
|
|
return data
|
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Given a Widget instance (*not* a Widget class), return a dictionary of
|
2006-12-09 02:54:53 +08:00
|
|
|
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):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return True if data differs from initial."""
|
2016-11-06 17:30:48 +08:00
|
|
|
# Always return False if the field is disabled since self.bound_data
|
|
|
|
# always uses the initial value in this case.
|
|
|
|
if self.disabled:
|
|
|
|
return False
|
2013-01-27 00:05:47 +08:00
|
|
|
try:
|
|
|
|
data = self.to_python(data)
|
2014-02-20 20:40:42 +08:00
|
|
|
if hasattr(self, '_coerce'):
|
2015-12-17 06:07:17 +08:00
|
|
|
return self._coerce(data) != self._coerce(initial)
|
2013-01-27 00:05:47 +08:00
|
|
|
except ValidationError:
|
2013-01-26 03:50:46 +08:00
|
|
|
return True
|
2015-12-17 06:07:17 +08:00
|
|
|
# For purposes of seeing whether something has changed, None is
|
|
|
|
# the same as an empty string, if the data or initial value we get
|
|
|
|
# is None, replace it with ''.
|
|
|
|
initial_value = initial if initial is not None else ''
|
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
|
|
|
|
2015-08-10 16:55:49 +08:00
|
|
|
def get_bound_field(self, form, field_name):
|
|
|
|
"""
|
|
|
|
Return a BoundField instance that will be used when accessing the form
|
|
|
|
field in a template.
|
|
|
|
"""
|
|
|
|
return BoundField(form, self, field_name)
|
|
|
|
|
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)
|
2019-10-08 15:38:28 +08:00
|
|
|
result.error_messages = self.error_messages.copy()
|
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):
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, max_length=None, min_length=None, strip=True, empty_value='', **kwargs):
|
2015-02-05 20:26:15 +08:00
|
|
|
self.max_length = max_length
|
|
|
|
self.min_length = min_length
|
|
|
|
self.strip = strip
|
2016-05-18 22:30:42 +08:00
|
|
|
self.empty_value = empty_value
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**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)))
|
2017-06-23 23:06:08 +08:00
|
|
|
self.validators.append(validators.ProhibitNullCharactersValidator())
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a string."""
|
2017-09-06 00:41:38 +08:00
|
|
|
if value not in self.empty_values:
|
|
|
|
value = str(value)
|
|
|
|
if self.strip:
|
|
|
|
value = value.strip()
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2016-05-18 22:30:42 +08:00
|
|
|
return self.empty_value
|
2015-02-05 20:26:15 +08:00
|
|
|
return value
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2006-12-09 02:54:53 +08:00
|
|
|
def widget_attrs(self, widget):
|
2017-01-21 21:13:44 +08:00
|
|
|
attrs = super().widget_attrs(widget)
|
2016-08-05 17:38:39 +08:00
|
|
|
if self.max_length is not None and not widget.is_hidden:
|
2007-08-05 13:14:46 +08:00
|
|
|
# The HTML attribute is maxlength, not max_length.
|
2016-04-19 08:57:05 +08:00
|
|
|
attrs['maxlength'] = str(self.max_length)
|
2016-08-05 17:38:39 +08:00
|
|
|
if self.min_length is not None and not widget.is_hidden:
|
2016-04-19 08:57:05 +08:00
|
|
|
# The HTML attribute is minlength, not min_length.
|
|
|
|
attrs['minlength'] = str(self.min_length)
|
2011-11-15 17:36:08 +08:00
|
|
|
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
|
|
|
}
|
2019-10-26 22:42:32 +08:00
|
|
|
re_decimal = _lazy_re_compile(r'\.0*\s*$')
|
2007-10-28 13:40:26 +08:00
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, max_value=None, min_value=None, **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
|
2017-01-21 21:13:44 +08:00
|
|
|
kwargs.setdefault('widget', super().widget)
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that int() can be called on the input. Return the result
|
|
|
|
of int() or None for empty values.
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().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)
|
2015-01-28 04:41:59 +08:00
|
|
|
# Strip trailing decimal and zeros.
|
2006-10-29 04:34:37 +08:00
|
|
|
try:
|
2017-04-22 01:52:26 +08:00
|
|
|
value = int(self.re_decimal.sub('', 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):
|
2017-01-21 21:13:44 +08:00
|
|
|
attrs = super().widget_attrs(widget)
|
2013-02-23 16:45:56 +08:00
|
|
|
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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that float() can be called on the input. Return the result
|
|
|
|
of float() or 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):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().validate(value)
|
2017-08-10 08:41:39 +08:00
|
|
|
if value in self.empty_values:
|
|
|
|
return
|
|
|
|
if not math.isfinite(value):
|
2013-09-07 00:54:48 +08:00
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
2017-01-21 21:13:44 +08:00
|
|
|
attrs = super().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.'),
|
2007-10-28 13:40:26 +08:00
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs):
|
2007-05-21 09:29:58 +08:00
|
|
|
self.max_digits, self.decimal_places = max_digits, decimal_places
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(max_value=max_value, min_value=min_value, **kwargs)
|
2015-04-15 06:11:12 +08:00
|
|
|
self.validators.append(validators.DecimalValidator(max_digits, decimal_places))
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def to_python(self, value):
|
2007-05-21 09:29:58 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that the input is a decimal number. Return a Decimal
|
|
|
|
instance or None for empty values. Ensure that there are no more
|
|
|
|
than max_digits in the number and no more than decimal_places digits
|
2007-05-21 09:29:58 +08:00
|
|
|
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)
|
2017-04-22 01:52:26 +08:00
|
|
|
value = str(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
|
|
|
|
2013-02-23 16:45:56 +08:00
|
|
|
def widget_attrs(self, widget):
|
2017-01-21 21:13:44 +08:00
|
|
|
attrs = super().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
|
2017-12-31 01:05:15 +08:00
|
|
|
step = str(Decimal(1).scaleb(-self.decimal_places)).lower()
|
2013-07-19 10:01:51 +08:00
|
|
|
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):
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, input_formats=None, **kwargs):
|
|
|
|
super().__init__(**kwargs)
|
2011-05-02 00:14:57 +08:00
|
|
|
if input_formats is not None:
|
|
|
|
self.input_formats = input_formats
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2017-01-27 02:35:39 +08:00
|
|
|
value = value.strip()
|
|
|
|
# Try to strptime against each input format.
|
|
|
|
for format in self.input_formats:
|
|
|
|
try:
|
|
|
|
return self.strptime(value, format)
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that the input can be converted to a date. Return a Python
|
2006-10-29 04:34:37 +08:00
|
|
|
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
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().to_python(value)
|
2006-10-29 04:34:37 +08:00
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
def strptime(self, value, format):
|
2017-01-12 06:17:25 +08:00
|
|
|
return datetime.datetime.strptime(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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that the input can be converted to a time. Return a Python
|
2006-12-15 04:35:32 +08:00
|
|
|
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
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().to_python(value)
|
2011-05-02 00:14:57 +08:00
|
|
|
|
|
|
|
def strptime(self, value, format):
|
2017-01-12 06:17:25 +08:00
|
|
|
return datetime.datetime.strptime(value, format).time()
|
2006-12-15 04:35:32 +08:00
|
|
|
|
2013-05-18 19:26:07 +08:00
|
|
|
|
2020-01-04 18:44:11 +08:00
|
|
|
class DateTimeFormatsIterator:
|
|
|
|
def __iter__(self):
|
|
|
|
yield from formats.get_format('DATETIME_INPUT_FORMATS')
|
|
|
|
yield from formats.get_format('DATE_INPUT_FORMATS')
|
|
|
|
|
|
|
|
|
2011-05-02 00:14:57 +08:00
|
|
|
class DateTimeField(BaseTemporalField):
|
2007-10-21 22:50:47 +08:00
|
|
|
widget = DateTimeInput
|
2020-01-04 18:44:11 +08:00
|
|
|
input_formats = DateTimeFormatsIterator()
|
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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that the input can be converted to a datetime. Return a
|
2006-10-29 04:34:37 +08:00
|
|
|
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)
|
2019-10-09 18:08:50 +08:00
|
|
|
try:
|
|
|
|
result = parse_datetime(value.strip())
|
|
|
|
except ValueError:
|
|
|
|
raise ValidationError(self.error_messages['invalid'], code='invalid')
|
|
|
|
if not result:
|
|
|
|
result = super().to_python(value)
|
2011-11-18 21:01:06 +08:00
|
|
|
return from_current_timezone(result)
|
2011-05-02 00:14:57 +08:00
|
|
|
|
|
|
|
def strptime(self, value, format):
|
2017-01-12 06:17:25 +08:00
|
|
|
return datetime.datetime.strptime(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.'),
|
2018-08-08 06:04:48 +08:00
|
|
|
'overflow': _('The number of days must be between {min_days} and {max_days}.')
|
2014-07-24 20:57:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2017-08-08 23:02:08 +08:00
|
|
|
try:
|
|
|
|
value = parse_duration(str(value))
|
|
|
|
except OverflowError:
|
2018-08-08 06:04:48 +08:00
|
|
|
raise ValidationError(self.error_messages['overflow'].format(
|
|
|
|
min_days=datetime.timedelta.min.days,
|
|
|
|
max_days=datetime.timedelta.max.days,
|
|
|
|
), code='overflow')
|
2014-07-24 20:57:24 +08:00
|
|
|
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):
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, regex, **kwargs):
|
2006-10-29 04:34:37 +08:00
|
|
|
"""
|
|
|
|
regex can be either a string or a compiled regular expression object.
|
|
|
|
"""
|
2015-02-05 20:26:15 +08:00
|
|
|
kwargs.setdefault('strip', False)
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**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):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(regex, str):
|
2017-01-19 05:52:25 +08:00
|
|
|
regex = re.compile(regex)
|
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
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
super().__init__(strip=True, **kwargs)
|
2010-10-07 23:50:36 +08:00
|
|
|
|
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."),
|
2017-01-27 03:58:33 +08:00
|
|
|
'max_length': ngettext_lazy(
|
2013-01-31 04:29:39 +08:00
|
|
|
'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
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, max_length=None, allow_empty_file=False, **kwargs):
|
2017-02-02 00:41:56 +08:00
|
|
|
self.max_length = max_length
|
|
|
|
self.allow_empty_file = allow_empty_file
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**kwargs)
|
2007-08-06 21:58:56 +08:00
|
|
|
|
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
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().clean(data)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
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):
|
2018-01-04 07:52:12 +08:00
|
|
|
return not self.disabled and data is not None
|
2013-01-26 03:50:46 +08:00
|
|
|
|
|
|
|
|
2007-08-06 21:58:56 +08:00
|
|
|
class ImageField(FileField):
|
2017-05-28 15:05:21 +08:00
|
|
|
default_validators = [validators.validate_image_file_extension]
|
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
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Check that the file-upload field data contains a valid image (GIF, JPG,
|
|
|
|
PNG, etc. -- whatever Pillow supports).
|
2007-08-06 21:58:56 +08:00
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
f = super().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
|
2015-06-16 23:24:59 +08:00
|
|
|
# Pillow doesn't detect the MIME type of all formats. In those
|
|
|
|
# cases, content_type will be None.
|
|
|
|
f.content_type = Image.MIME.get(image.format)
|
2017-01-08 03:13:29 +08:00
|
|
|
except Exception as exc:
|
2014-03-21 22:54:53 +08:00
|
|
|
# Pillow doesn't recognize it as an image.
|
2017-01-08 03:13:29 +08:00
|
|
|
raise ValidationError(
|
2013-06-06 02:55:05 +08:00
|
|
|
self.error_messages['invalid_image'],
|
|
|
|
code='invalid_image',
|
2017-01-08 03:13:29 +08:00
|
|
|
) from exc
|
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
|
|
|
|
2018-04-03 11:06:08 +08:00
|
|
|
def widget_attrs(self, widget):
|
|
|
|
attrs = super().widget_attrs(widget)
|
|
|
|
if isinstance(widget, FileInput) and 'accept' not in widget.attrs:
|
|
|
|
attrs.setdefault('accept', 'image/*')
|
|
|
|
return attrs
|
|
|
|
|
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
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
super().__init__(strip=True, **kwargs)
|
2016-07-03 22:41:59 +08:00
|
|
|
|
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):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a list of url parts via urlparse.urlsplit(), or raise
|
|
|
|
ValidationError for some malformed URLs.
|
2011-09-10 06:57:12 +08:00
|
|
|
"""
|
|
|
|
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
|
|
|
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().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-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):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a Python boolean object."""
|
2007-11-30 03:22:03 +08:00
|
|
|
# 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.
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(value, str) and value.lower() in ('false', '0'):
|
2008-06-30 18:44:56 +08:00
|
|
|
value = False
|
|
|
|
else:
|
|
|
|
value = bool(value)
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().to_python(value)
|
2013-01-26 23:39:20 +08:00
|
|
|
|
|
|
|
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):
|
2017-07-13 22:55:32 +08:00
|
|
|
if self.disabled:
|
|
|
|
return False
|
2016-04-25 03:06:30 +08:00
|
|
|
# Sometimes data or initial may be a string equivalent of a boolean
|
|
|
|
# so we should run it through to_python first to get a boolean value
|
|
|
|
return self.to_python(initial) != self.to_python(data)
|
2013-01-26 03:50:46 +08:00
|
|
|
|
|
|
|
|
2007-01-24 13:23:19 +08:00
|
|
|
class NullBooleanField(BooleanField):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
A field whose valid values are None, True, and False. Clean invalid values
|
|
|
|
to None.
|
2007-01-24 13:23:19 +08:00
|
|
|
"""
|
|
|
|
widget = NullBooleanSelect
|
|
|
|
|
2010-01-05 11:56:19 +08:00
|
|
|
def to_python(self, value):
|
2008-08-28 23:06:18 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Explicitly check 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
|
2017-01-25 05:23:56 +08:00
|
|
|
the Booleanfield, this field must check for True because it doesn't
|
|
|
|
use 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
|
|
|
|
|
2013-01-26 03:50:46 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CallableChoiceIterator:
|
2014-10-28 04:21:59 +08:00
|
|
|
def __init__(self, choices_func):
|
|
|
|
self.choices_func = choices_func
|
|
|
|
|
|
|
|
def __iter__(self):
|
2017-02-24 09:06:01 +08:00
|
|
|
yield from self.choices_func()
|
2014-10-28 04:21:59 +08:00
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, choices=(), **kwargs):
|
|
|
|
super().__init__(**kwargs)
|
2006-11-02 11:16:12 +08:00
|
|
|
self.choices = choices
|
|
|
|
|
2011-06-17 00:34:38 +08:00
|
|
|
def __deepcopy__(self, memo):
|
2017-01-21 21:13:44 +08:00
|
|
|
result = super().__deepcopy__(memo)
|
2011-06-17 00:34:38 +08:00
|
|
|
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):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Return a string."""
|
2013-03-07 16:21:59 +08:00
|
|
|
if value in self.empty_values:
|
2012-06-08 00:08:47 +08:00
|
|
|
return ''
|
2017-04-22 01:52:26 +08:00
|
|
|
return str(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def validate(self, value):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Validate that the input is in self.choices."""
|
2017-01-21 21:13:44 +08:00
|
|
|
super().validate(value)
|
2010-01-05 11:56:19 +08:00
|
|
|
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):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Check to see if the provided value is a valid choice."""
|
2017-04-22 01:52:26 +08:00
|
|
|
text_value = str(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:
|
2017-04-22 01:52:26 +08:00
|
|
|
if value == k2 or text_value == str(k2):
|
2008-07-19 15:53:02 +08:00
|
|
|
return True
|
|
|
|
else:
|
2017-04-22 01:52:26 +08:00
|
|
|
if value == k or text_value == str(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):
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, coerce=lambda val: val, empty_value='', **kwargs):
|
2017-02-02 00:41:56 +08:00
|
|
|
self.coerce = coerce
|
|
|
|
self.empty_value = empty_value
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**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):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().clean(value)
|
2013-11-19 01:24:56 +08:00
|
|
|
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')
|
2017-04-22 01:52:26 +08:00
|
|
|
return [str(val) for val in value]
|
2010-01-05 11:56:19 +08:00
|
|
|
|
|
|
|
def validate(self, value):
|
2017-01-25 05:23:56 +08:00
|
|
|
"""Validate that the input is a list or tuple."""
|
2006-11-02 11:16:12 +08:00
|
|
|
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):
|
2017-07-13 22:55:32 +08:00
|
|
|
if self.disabled:
|
|
|
|
return False
|
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
|
2017-06-02 07:08:59 +08:00
|
|
|
initial_set = {str(value) for value in initial}
|
|
|
|
data_set = {str(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):
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, coerce=lambda val: val, **kwargs):
|
2017-02-02 00:41:56 +08:00
|
|
|
self.coerce = coerce
|
2010-12-05 12:47:19 +08:00
|
|
|
self.empty_value = kwargs.pop('empty_value', [])
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**kwargs)
|
2010-12-05 12:47:19 +08:00
|
|
|
|
2013-11-19 01:24:56 +08:00
|
|
|
def _coerce(self, value):
|
2010-12-05 12:47:19 +08:00
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate that the values are in self.choices and can be coerced to the
|
2010-12-05 12:47:19 +08:00
|
|
|
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):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().clean(value)
|
2013-11-19 01:24:56 +08:00
|
|
|
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:
|
2017-01-21 21:13:44 +08:00
|
|
|
super().validate(value)
|
2013-03-14 21:45:41 +08:00
|
|
|
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.
|
|
|
|
"""
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, fields, **kwargs):
|
|
|
|
super().__init__(**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):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate the given value against all of self.fields, which is a
|
2006-11-05 04:49:59 +08:00
|
|
|
list of Field instances.
|
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
super().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):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Aggregate 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
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, fields, *, require_all_fields=True, **kwargs):
|
2017-02-02 00:41:56 +08:00
|
|
|
self.require_all_fields = require_all_fields
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**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'])
|
2018-01-06 04:49:54 +08:00
|
|
|
if self.disabled:
|
|
|
|
f.disabled = True
|
2013-05-07 17:06:03 +08:00
|
|
|
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):
|
2017-01-21 21:13:44 +08:00
|
|
|
result = super().__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):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Validate every value in the given list. A value is validated against
|
2007-01-24 04:23:07 +08:00
|
|
|
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 = []
|
2018-01-06 04:49:54 +08:00
|
|
|
if self.disabled and not isinstance(value, list):
|
|
|
|
value = self.widget.decompress(value)
|
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):
|
|
|
|
"""
|
2017-01-25 05:23:56 +08:00
|
|
|
Return a single value for the given list of values. The values can be
|
2007-01-24 04:23:07 +08:00
|
|
|
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):
|
2017-07-13 22:55:32 +08:00
|
|
|
if self.disabled:
|
|
|
|
return False
|
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):
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, path, *, match=None, recursive=False, allow_files=True,
|
|
|
|
allow_folders=False, **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
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(choices=(), **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:
|
2017-07-16 14:00:03 +08:00
|
|
|
for f in sorted(files):
|
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)))
|
|
|
|
if self.allow_folders:
|
2017-07-16 14:00:03 +08:00
|
|
|
for f in sorted(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:
|
2018-08-20 07:21:57 +08:00
|
|
|
choices = []
|
|
|
|
for f in os.scandir(self.path):
|
|
|
|
if f.name == '__pycache__':
|
|
|
|
continue
|
|
|
|
if (((self.allow_files and f.is_file()) or
|
|
|
|
(self.allow_folders and f.is_dir())) and
|
|
|
|
(self.match is None or self.match_re.search(f.name))):
|
|
|
|
choices.append((f.path, f.name))
|
2018-08-29 18:19:32 +08:00
|
|
|
choices.sort(key=operator.itemgetter(1))
|
2018-08-20 07:21:57 +08:00
|
|
|
self.choices.extend(choices)
|
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
|
|
|
}
|
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, input_date_formats=None, input_time_formats=None, **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
|
|
|
)
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(fields, **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):
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, protocol='both', unpack_ipv4=False, **kwargs):
|
2011-06-11 21:48:24 +08:00
|
|
|
self.unpack_ipv4 = unpack_ipv4
|
2013-03-14 23:19:59 +08:00
|
|
|
self.default_validators = validators.ip_address_validators(protocol, unpack_ipv4)[0]
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**kwargs)
|
2011-06-11 21:48:24 +08:00
|
|
|
|
|
|
|
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
|
|
|
|
2017-06-03 22:49:01 +08:00
|
|
|
def __init__(self, *, allow_unicode=False, **kwargs):
|
2017-02-02 00:41:56 +08:00
|
|
|
self.allow_unicode = allow_unicode
|
2015-04-16 06:28:49 +08:00
|
|
|
if self.allow_unicode:
|
|
|
|
self.default_validators = [validators.validate_unicode_slug]
|
2017-06-03 22:49:01 +08:00
|
|
|
super().__init__(**kwargs)
|
2015-04-16 06:28:49 +08:00
|
|
|
|
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):
|
2018-08-18 06:43:35 +08:00
|
|
|
return str(value)
|
2014-07-15 17:35:29 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
def to_python(self, value):
|
2017-01-21 21:13:44 +08:00
|
|
|
value = super().to_python(value)
|
2014-07-15 17:35:29 +08:00
|
|
|
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
|
2019-06-09 08:56:37 +08:00
|
|
|
|
|
|
|
|
|
|
|
class InvalidJSONInput(str):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class JSONString(str):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class JSONField(CharField):
|
|
|
|
default_error_messages = {
|
|
|
|
'invalid': _('Enter a valid JSON.'),
|
|
|
|
}
|
|
|
|
widget = Textarea
|
|
|
|
|
|
|
|
def __init__(self, encoder=None, decoder=None, **kwargs):
|
|
|
|
self.encoder = encoder
|
|
|
|
self.decoder = decoder
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
if self.disabled:
|
|
|
|
return value
|
|
|
|
if value in self.empty_values:
|
|
|
|
return None
|
|
|
|
elif isinstance(value, (list, dict, int, float, JSONString)):
|
|
|
|
return value
|
|
|
|
try:
|
|
|
|
converted = json.loads(value, cls=self.decoder)
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
raise ValidationError(
|
|
|
|
self.error_messages['invalid'],
|
|
|
|
code='invalid',
|
|
|
|
params={'value': value},
|
|
|
|
)
|
|
|
|
if isinstance(converted, str):
|
|
|
|
return JSONString(converted)
|
|
|
|
else:
|
|
|
|
return converted
|
|
|
|
|
|
|
|
def bound_data(self, data, initial):
|
|
|
|
if self.disabled:
|
|
|
|
return initial
|
|
|
|
try:
|
|
|
|
return json.loads(data, cls=self.decoder)
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
return InvalidJSONInput(data)
|
|
|
|
|
|
|
|
def prepare_value(self, value):
|
|
|
|
if isinstance(value, InvalidJSONInput):
|
|
|
|
return value
|
2020-10-08 21:51:14 +08:00
|
|
|
return json.dumps(value, ensure_ascii=False, cls=self.encoder)
|
2019-06-09 08:56:37 +08:00
|
|
|
|
|
|
|
def has_changed(self, initial, data):
|
|
|
|
if super().has_changed(initial, data):
|
|
|
|
return True
|
|
|
|
# For purposes of seeing whether something has changed, True isn't the
|
|
|
|
# same as 1 and the order of keys doesn't matter.
|
|
|
|
return (
|
|
|
|
json.dumps(initial, sort_keys=True, cls=self.encoder) !=
|
|
|
|
json.dumps(self.to_python(data), sort_keys=True, cls=self.encoder)
|
|
|
|
)
|