PageRenderTime 85ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/packages/django/forms/fields.py

https://gitlab.com/gregtyka/Scryve-Webapp
Python | 883 lines | 769 code | 33 blank | 81 comment | 59 complexity | f99a6e58ce84ecd1a859f84fd07938c9 MD5 | raw file
  1. """
  2. Field classes.
  3. """
  4. import datetime
  5. import os
  6. import re
  7. import time
  8. import urlparse
  9. import warnings
  10. from decimal import Decimal, DecimalException
  11. try:
  12. from cStringIO import StringIO
  13. except ImportError:
  14. from StringIO import StringIO
  15. from django.core.exceptions import ValidationError
  16. from django.core import validators
  17. import django.utils.copycompat as copy
  18. from django.utils import formats
  19. from django.utils.translation import ugettext_lazy as _
  20. from django.utils.encoding import smart_unicode, smart_str
  21. from django.utils.functional import lazy
  22. # Provide this import for backwards compatibility.
  23. from django.core.validators import EMPTY_VALUES
  24. from util import ErrorList
  25. from widgets import TextInput, PasswordInput, HiddenInput, MultipleHiddenInput, \
  26. FileInput, CheckboxInput, Select, NullBooleanSelect, SelectMultiple, \
  27. DateInput, DateTimeInput, TimeInput, SplitDateTimeWidget, SplitHiddenDateTimeWidget
  28. __all__ = (
  29. 'Field', 'CharField', 'IntegerField',
  30. 'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
  31. 'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
  32. 'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField', 'TimeField',
  33. 'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
  34. 'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
  35. 'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
  36. 'SplitDateTimeField', 'IPAddressField', 'FilePathField', 'SlugField',
  37. 'TypedChoiceField'
  38. )
  39. def en_format(name):
  40. """
  41. Helper function to stay backward compatible.
  42. """
  43. from django.conf.locale.en import formats
  44. warnings.warn(
  45. "`django.forms.fields.DEFAULT_%s` is deprecated; use `django.utils.formats.get_format('%s')` instead." % (name, name),
  46. PendingDeprecationWarning
  47. )
  48. return getattr(formats, name)
  49. DEFAULT_DATE_INPUT_FORMATS = lazy(lambda: en_format('DATE_INPUT_FORMATS'), tuple, list)()
  50. DEFAULT_TIME_INPUT_FORMATS = lazy(lambda: en_format('TIME_INPUT_FORMATS'), tuple, list)()
  51. DEFAULT_DATETIME_INPUT_FORMATS = lazy(lambda: en_format('DATETIME_INPUT_FORMATS'), tuple, list)()
  52. class Field(object):
  53. widget = TextInput # Default widget to use when rendering this type of Field.
  54. hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
  55. default_validators = [] # Default set of validators
  56. default_error_messages = {
  57. 'required': _(u'This field is required.'),
  58. 'invalid': _(u'Enter a valid value.'),
  59. }
  60. # Tracks each time a Field instance is created. Used to retain order.
  61. creation_counter = 0
  62. def __init__(self, required=True, widget=None, label=None, initial=None,
  63. help_text=None, error_messages=None, show_hidden_initial=False,
  64. validators=[], localize=False):
  65. # required -- Boolean that specifies whether the field is required.
  66. # True by default.
  67. # widget -- A Widget class, or instance of a Widget class, that should
  68. # be used for this Field when displaying it. Each Field has a
  69. # default Widget that it'll use if you don't specify this. In
  70. # most cases, the default widget is TextInput.
  71. # label -- A verbose name for this field, for use in displaying this
  72. # field in a form. By default, Django will use a "pretty"
  73. # version of the form field name, if the Field is part of a
  74. # Form.
  75. # initial -- A value to use in this Field's initial display. This value
  76. # is *not* used as a fallback if data isn't given.
  77. # help_text -- An optional string to use as "help text" for this Field.
  78. # error_messages -- An optional dictionary to override the default
  79. # messages that the field will raise.
  80. # show_hidden_initial -- Boolean that specifies if it is needed to render a
  81. # hidden widget with initial value after widget.
  82. # validators -- List of addtional validators to use
  83. # localize -- Boolean that specifies if the field should be localized.
  84. if label is not None:
  85. label = smart_unicode(label)
  86. self.required, self.label, self.initial = required, label, initial
  87. self.show_hidden_initial = show_hidden_initial
  88. if help_text is None:
  89. self.help_text = u''
  90. else:
  91. self.help_text = smart_unicode(help_text)
  92. widget = widget or self.widget
  93. if isinstance(widget, type):
  94. widget = widget()
  95. # Trigger the localization machinery if needed.
  96. self.localize = localize
  97. if self.localize:
  98. widget.is_localized = True
  99. # Hook into self.widget_attrs() for any Field-specific HTML attributes.
  100. extra_attrs = self.widget_attrs(widget)
  101. if extra_attrs:
  102. widget.attrs.update(extra_attrs)
  103. self.widget = widget
  104. # Increase the creation counter, and save our local copy.
  105. self.creation_counter = Field.creation_counter
  106. Field.creation_counter += 1
  107. messages = {}
  108. for c in reversed(self.__class__.__mro__):
  109. messages.update(getattr(c, 'default_error_messages', {}))
  110. messages.update(error_messages or {})
  111. self.error_messages = messages
  112. self.validators = self.default_validators + validators
  113. def prepare_value(self, value):
  114. return value
  115. def to_python(self, value):
  116. return value
  117. def validate(self, value):
  118. if value in validators.EMPTY_VALUES and self.required:
  119. raise ValidationError(self.error_messages['required'])
  120. def run_validators(self, value):
  121. if value in validators.EMPTY_VALUES:
  122. return
  123. errors = []
  124. for v in self.validators:
  125. try:
  126. v(value)
  127. except ValidationError, e:
  128. if hasattr(e, 'code') and e.code in self.error_messages:
  129. message = self.error_messages[e.code]
  130. if e.params:
  131. message = message % e.params
  132. errors.append(message)
  133. else:
  134. errors.extend(e.messages)
  135. if errors:
  136. raise ValidationError(errors)
  137. def clean(self, value):
  138. """
  139. Validates the given value and returns its "cleaned" value as an
  140. appropriate Python object.
  141. Raises ValidationError for any errors.
  142. """
  143. value = self.to_python(value)
  144. self.validate(value)
  145. self.run_validators(value)
  146. return value
  147. def widget_attrs(self, widget):
  148. """
  149. Given a Widget instance (*not* a Widget class), returns a dictionary of
  150. any HTML attributes that should be added to the Widget, based on this
  151. Field.
  152. """
  153. return {}
  154. def __deepcopy__(self, memo):
  155. result = copy.copy(self)
  156. memo[id(self)] = result
  157. result.widget = copy.deepcopy(self.widget, memo)
  158. return result
  159. class CharField(Field):
  160. def __init__(self, max_length=None, min_length=None, *args, **kwargs):
  161. self.max_length, self.min_length = max_length, min_length
  162. super(CharField, self).__init__(*args, **kwargs)
  163. if min_length is not None:
  164. self.validators.append(validators.MinLengthValidator(min_length))
  165. if max_length is not None:
  166. self.validators.append(validators.MaxLengthValidator(max_length))
  167. def to_python(self, value):
  168. "Returns a Unicode object."
  169. if value in validators.EMPTY_VALUES:
  170. return u''
  171. return smart_unicode(value)
  172. def widget_attrs(self, widget):
  173. if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
  174. # The HTML attribute is maxlength, not max_length.
  175. return {'maxlength': str(self.max_length)}
  176. class IntegerField(Field):
  177. default_error_messages = {
  178. 'invalid': _(u'Enter a whole number.'),
  179. 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
  180. 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
  181. }
  182. def __init__(self, max_value=None, min_value=None, *args, **kwargs):
  183. super(IntegerField, self).__init__(*args, **kwargs)
  184. if max_value is not None:
  185. self.validators.append(validators.MaxValueValidator(max_value))
  186. if min_value is not None:
  187. self.validators.append(validators.MinValueValidator(min_value))
  188. def to_python(self, value):
  189. """
  190. Validates that int() can be called on the input. Returns the result
  191. of int(). Returns None for empty values.
  192. """
  193. value = super(IntegerField, self).to_python(value)
  194. if value in validators.EMPTY_VALUES:
  195. return None
  196. if self.localize:
  197. value = formats.sanitize_separators(value)
  198. try:
  199. value = int(str(value))
  200. except (ValueError, TypeError):
  201. raise ValidationError(self.error_messages['invalid'])
  202. return value
  203. class FloatField(IntegerField):
  204. default_error_messages = {
  205. 'invalid': _(u'Enter a number.'),
  206. }
  207. def to_python(self, value):
  208. """
  209. Validates that float() can be called on the input. Returns the result
  210. of float(). Returns None for empty values.
  211. """
  212. value = super(IntegerField, self).to_python(value)
  213. if value in validators.EMPTY_VALUES:
  214. return None
  215. if self.localize:
  216. value = formats.sanitize_separators(value)
  217. try:
  218. value = float(value)
  219. except (ValueError, TypeError):
  220. raise ValidationError(self.error_messages['invalid'])
  221. return value
  222. class DecimalField(Field):
  223. default_error_messages = {
  224. 'invalid': _(u'Enter a number.'),
  225. 'max_value': _(u'Ensure this value is less than or equal to %(limit_value)s.'),
  226. 'min_value': _(u'Ensure this value is greater than or equal to %(limit_value)s.'),
  227. 'max_digits': _('Ensure that there are no more than %s digits in total.'),
  228. 'max_decimal_places': _('Ensure that there are no more than %s decimal places.'),
  229. 'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.')
  230. }
  231. def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
  232. self.max_digits, self.decimal_places = max_digits, decimal_places
  233. Field.__init__(self, *args, **kwargs)
  234. if max_value is not None:
  235. self.validators.append(validators.MaxValueValidator(max_value))
  236. if min_value is not None:
  237. self.validators.append(validators.MinValueValidator(min_value))
  238. def to_python(self, value):
  239. """
  240. Validates that the input is a decimal number. Returns a Decimal
  241. instance. Returns None for empty values. Ensures that there are no more
  242. than max_digits in the number, and no more than decimal_places digits
  243. after the decimal point.
  244. """
  245. if value in validators.EMPTY_VALUES:
  246. return None
  247. if self.localize:
  248. value = formats.sanitize_separators(value)
  249. value = smart_str(value).strip()
  250. try:
  251. value = Decimal(value)
  252. except DecimalException:
  253. raise ValidationError(self.error_messages['invalid'])
  254. return value
  255. def validate(self, value):
  256. super(DecimalField, self).validate(value)
  257. if value in validators.EMPTY_VALUES:
  258. return
  259. # Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
  260. # since it is never equal to itself. However, NaN is the only value that
  261. # isn't equal to itself, so we can use this to identify NaN
  262. if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
  263. raise ValidationError(self.error_messages['invalid'])
  264. sign, digittuple, exponent = value.as_tuple()
  265. decimals = abs(exponent)
  266. # digittuple doesn't include any leading zeros.
  267. digits = len(digittuple)
  268. if decimals > digits:
  269. # We have leading zeros up to or past the decimal point. Count
  270. # everything past the decimal point as a digit. We do not count
  271. # 0 before the decimal point as a digit since that would mean
  272. # we would not allow max_digits = decimal_places.
  273. digits = decimals
  274. whole_digits = digits - decimals
  275. if self.max_digits is not None and digits > self.max_digits:
  276. raise ValidationError(self.error_messages['max_digits'] % self.max_digits)
  277. if self.decimal_places is not None and decimals > self.decimal_places:
  278. raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places)
  279. if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places):
  280. raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places))
  281. return value
  282. class DateField(Field):
  283. widget = DateInput
  284. default_error_messages = {
  285. 'invalid': _(u'Enter a valid date.'),
  286. }
  287. def __init__(self, input_formats=None, *args, **kwargs):
  288. super(DateField, self).__init__(*args, **kwargs)
  289. self.input_formats = input_formats
  290. def to_python(self, value):
  291. """
  292. Validates that the input can be converted to a date. Returns a Python
  293. datetime.date object.
  294. """
  295. if value in validators.EMPTY_VALUES:
  296. return None
  297. if isinstance(value, datetime.datetime):
  298. return value.date()
  299. if isinstance(value, datetime.date):
  300. return value
  301. for format in self.input_formats or formats.get_format('DATE_INPUT_FORMATS'):
  302. try:
  303. return datetime.date(*time.strptime(value, format)[:3])
  304. except ValueError:
  305. continue
  306. raise ValidationError(self.error_messages['invalid'])
  307. class TimeField(Field):
  308. widget = TimeInput
  309. default_error_messages = {
  310. 'invalid': _(u'Enter a valid time.')
  311. }
  312. def __init__(self, input_formats=None, *args, **kwargs):
  313. super(TimeField, self).__init__(*args, **kwargs)
  314. self.input_formats = input_formats
  315. def to_python(self, value):
  316. """
  317. Validates that the input can be converted to a time. Returns a Python
  318. datetime.time object.
  319. """
  320. if value in validators.EMPTY_VALUES:
  321. return None
  322. if isinstance(value, datetime.time):
  323. return value
  324. for format in self.input_formats or formats.get_format('TIME_INPUT_FORMATS'):
  325. try:
  326. return datetime.time(*time.strptime(value, format)[3:6])
  327. except ValueError:
  328. continue
  329. raise ValidationError(self.error_messages['invalid'])
  330. class DateTimeField(Field):
  331. widget = DateTimeInput
  332. default_error_messages = {
  333. 'invalid': _(u'Enter a valid date/time.'),
  334. }
  335. def __init__(self, input_formats=None, *args, **kwargs):
  336. super(DateTimeField, self).__init__(*args, **kwargs)
  337. self.input_formats = input_formats
  338. def to_python(self, value):
  339. """
  340. Validates that the input can be converted to a datetime. Returns a
  341. Python datetime.datetime object.
  342. """
  343. if value in validators.EMPTY_VALUES:
  344. return None
  345. if isinstance(value, datetime.datetime):
  346. return value
  347. if isinstance(value, datetime.date):
  348. return datetime.datetime(value.year, value.month, value.day)
  349. if isinstance(value, list):
  350. # Input comes from a SplitDateTimeWidget, for example. So, it's two
  351. # components: date and time.
  352. if len(value) != 2:
  353. raise ValidationError(self.error_messages['invalid'])
  354. value = '%s %s' % tuple(value)
  355. for format in self.input_formats or formats.get_format('DATETIME_INPUT_FORMATS'):
  356. try:
  357. return datetime.datetime(*time.strptime(value, format)[:6])
  358. except ValueError:
  359. continue
  360. raise ValidationError(self.error_messages['invalid'])
  361. class RegexField(CharField):
  362. def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
  363. """
  364. regex can be either a string or a compiled regular expression object.
  365. error_message is an optional error message to use, if
  366. 'Enter a valid value' is too generic for you.
  367. """
  368. # error_message is just kept for backwards compatibility:
  369. if error_message:
  370. error_messages = kwargs.get('error_messages') or {}
  371. error_messages['invalid'] = error_message
  372. kwargs['error_messages'] = error_messages
  373. super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
  374. if isinstance(regex, basestring):
  375. regex = re.compile(regex)
  376. self.regex = regex
  377. self.validators.append(validators.RegexValidator(regex=regex))
  378. class EmailField(CharField):
  379. default_error_messages = {
  380. 'invalid': _(u'Enter a valid e-mail address.'),
  381. }
  382. default_validators = [validators.validate_email]
  383. class FileField(Field):
  384. widget = FileInput
  385. default_error_messages = {
  386. 'invalid': _(u"No file was submitted. Check the encoding type on the form."),
  387. 'missing': _(u"No file was submitted."),
  388. 'empty': _(u"The submitted file is empty."),
  389. 'max_length': _(u'Ensure this filename has at most %(max)d characters (it has %(length)d).'),
  390. }
  391. def __init__(self, *args, **kwargs):
  392. self.max_length = kwargs.pop('max_length', None)
  393. super(FileField, self).__init__(*args, **kwargs)
  394. def to_python(self, data):
  395. if data in validators.EMPTY_VALUES:
  396. return None
  397. # UploadedFile objects should have name and size attributes.
  398. try:
  399. file_name = data.name
  400. file_size = data.size
  401. except AttributeError:
  402. raise ValidationError(self.error_messages['invalid'])
  403. if self.max_length is not None and len(file_name) > self.max_length:
  404. error_values = {'max': self.max_length, 'length': len(file_name)}
  405. raise ValidationError(self.error_messages['max_length'] % error_values)
  406. if not file_name:
  407. raise ValidationError(self.error_messages['invalid'])
  408. if not file_size:
  409. raise ValidationError(self.error_messages['empty'])
  410. return data
  411. def clean(self, data, initial=None):
  412. if not data and initial:
  413. return initial
  414. return super(FileField, self).clean(data)
  415. class ImageField(FileField):
  416. default_error_messages = {
  417. 'invalid_image': _(u"Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
  418. }
  419. def to_python(self, data):
  420. """
  421. Checks that the file-upload field data contains a valid image (GIF, JPG,
  422. PNG, possibly others -- whatever the Python Imaging Library supports).
  423. """
  424. f = super(ImageField, self).to_python(data)
  425. if f is None:
  426. return None
  427. # Try to import PIL in either of the two ways it can end up installed.
  428. try:
  429. from PIL import Image
  430. except ImportError:
  431. import Image
  432. # We need to get a file object for PIL. We might have a path or we might
  433. # have to read the data into memory.
  434. if hasattr(data, 'temporary_file_path'):
  435. file = data.temporary_file_path()
  436. else:
  437. if hasattr(data, 'read'):
  438. file = StringIO(data.read())
  439. else:
  440. file = StringIO(data['content'])
  441. try:
  442. # load() is the only method that can spot a truncated JPEG,
  443. # but it cannot be called sanely after verify()
  444. trial_image = Image.open(file)
  445. trial_image.load()
  446. # Since we're about to use the file again we have to reset the
  447. # file object if possible.
  448. if hasattr(file, 'reset'):
  449. file.reset()
  450. # verify() is the only method that can spot a corrupt PNG,
  451. # but it must be called immediately after the constructor
  452. trial_image = Image.open(file)
  453. trial_image.verify()
  454. except ImportError:
  455. # Under PyPy, it is possible to import PIL. However, the underlying
  456. # _imaging C module isn't available, so an ImportError will be
  457. # raised. Catch and re-raise.
  458. raise
  459. except Exception: # Python Imaging Library doesn't recognize it as an image
  460. raise ValidationError(self.error_messages['invalid_image'])
  461. if hasattr(f, 'seek') and callable(f.seek):
  462. f.seek(0)
  463. return f
  464. class URLField(CharField):
  465. default_error_messages = {
  466. 'invalid': _(u'Enter a valid URL.'),
  467. 'invalid_link': _(u'This URL appears to be a broken link.'),
  468. }
  469. def __init__(self, max_length=None, min_length=None, verify_exists=False,
  470. validator_user_agent=validators.URL_VALIDATOR_USER_AGENT, *args, **kwargs):
  471. super(URLField, self).__init__(max_length, min_length, *args,
  472. **kwargs)
  473. self.validators.append(validators.URLValidator(verify_exists=verify_exists, validator_user_agent=validator_user_agent))
  474. def to_python(self, value):
  475. if value:
  476. if '://' not in value:
  477. # If no URL scheme given, assume http://
  478. value = u'http://%s' % value
  479. url_fields = list(urlparse.urlsplit(value))
  480. if not url_fields[2]:
  481. # the path portion may need to be added before query params
  482. url_fields[2] = '/'
  483. value = urlparse.urlunsplit(url_fields)
  484. return super(URLField, self).to_python(value)
  485. class BooleanField(Field):
  486. widget = CheckboxInput
  487. def to_python(self, value):
  488. """Returns a Python boolean object."""
  489. # Explicitly check for the string 'False', which is what a hidden field
  490. # will submit for False. Also check for '0', since this is what
  491. # RadioSelect will provide. Because bool("True") == bool('1') == True,
  492. # we don't need to handle that explicitly.
  493. if value in ('False', '0'):
  494. value = False
  495. else:
  496. value = bool(value)
  497. value = super(BooleanField, self).to_python(value)
  498. if not value and self.required:
  499. raise ValidationError(self.error_messages['required'])
  500. return value
  501. class NullBooleanField(BooleanField):
  502. """
  503. A field whose valid values are None, True and False. Invalid values are
  504. cleaned to None.
  505. """
  506. widget = NullBooleanSelect
  507. def to_python(self, value):
  508. """
  509. Explicitly checks for the string 'True' and 'False', which is what a
  510. hidden field will submit for True and False, and for '1' and '0', which
  511. is what a RadioField will submit. Unlike the Booleanfield we need to
  512. explicitly check for True, because we are not using the bool() function
  513. """
  514. if value in (True, 'True', '1'):
  515. return True
  516. elif value in (False, 'False', '0'):
  517. return False
  518. else:
  519. return None
  520. def validate(self, value):
  521. pass
  522. class ChoiceField(Field):
  523. widget = Select
  524. default_error_messages = {
  525. 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
  526. }
  527. def __init__(self, choices=(), required=True, widget=None, label=None,
  528. initial=None, help_text=None, *args, **kwargs):
  529. super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
  530. initial=initial, help_text=help_text, *args, **kwargs)
  531. self.choices = choices
  532. def _get_choices(self):
  533. return self._choices
  534. def _set_choices(self, value):
  535. # Setting choices also sets the choices on the widget.
  536. # choices can be any iterable, but we call list() on it because
  537. # it will be consumed more than once.
  538. self._choices = self.widget.choices = list(value)
  539. choices = property(_get_choices, _set_choices)
  540. def to_python(self, value):
  541. "Returns a Unicode object."
  542. if value in validators.EMPTY_VALUES:
  543. return u''
  544. return smart_unicode(value)
  545. def validate(self, value):
  546. """
  547. Validates that the input is in self.choices.
  548. """
  549. super(ChoiceField, self).validate(value)
  550. if value and not self.valid_value(value):
  551. raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
  552. def valid_value(self, value):
  553. "Check to see if the provided value is a valid choice"
  554. for k, v in self.choices:
  555. if isinstance(v, (list, tuple)):
  556. # This is an optgroup, so look inside the group for options
  557. for k2, v2 in v:
  558. if value == smart_unicode(k2):
  559. return True
  560. else:
  561. if value == smart_unicode(k):
  562. return True
  563. return False
  564. class TypedChoiceField(ChoiceField):
  565. def __init__(self, *args, **kwargs):
  566. self.coerce = kwargs.pop('coerce', lambda val: val)
  567. self.empty_value = kwargs.pop('empty_value', '')
  568. super(TypedChoiceField, self).__init__(*args, **kwargs)
  569. def to_python(self, value):
  570. """
  571. Validate that the value is in self.choices and can be coerced to the
  572. right type.
  573. """
  574. value = super(TypedChoiceField, self).to_python(value)
  575. super(TypedChoiceField, self).validate(value)
  576. if value == self.empty_value or value in validators.EMPTY_VALUES:
  577. return self.empty_value
  578. try:
  579. value = self.coerce(value)
  580. except (ValueError, TypeError, ValidationError):
  581. raise ValidationError(self.error_messages['invalid_choice'] % {'value': value})
  582. return value
  583. def validate(self, value):
  584. pass
  585. class MultipleChoiceField(ChoiceField):
  586. hidden_widget = MultipleHiddenInput
  587. widget = SelectMultiple
  588. default_error_messages = {
  589. 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),
  590. 'invalid_list': _(u'Enter a list of values.'),
  591. }
  592. def to_python(self, value):
  593. if not value:
  594. return []
  595. elif not isinstance(value, (list, tuple)):
  596. raise ValidationError(self.error_messages['invalid_list'])
  597. return [smart_unicode(val) for val in value]
  598. def validate(self, value):
  599. """
  600. Validates that the input is a list or tuple.
  601. """
  602. if self.required and not value:
  603. raise ValidationError(self.error_messages['required'])
  604. # Validate that each value in the value list is in self.choices.
  605. for val in value:
  606. if not self.valid_value(val):
  607. raise ValidationError(self.error_messages['invalid_choice'] % {'value': val})
  608. class ComboField(Field):
  609. """
  610. A Field whose clean() method calls multiple Field clean() methods.
  611. """
  612. def __init__(self, fields=(), *args, **kwargs):
  613. super(ComboField, self).__init__(*args, **kwargs)
  614. # Set 'required' to False on the individual fields, because the
  615. # required validation will be handled by ComboField, not by those
  616. # individual fields.
  617. for f in fields:
  618. f.required = False
  619. self.fields = fields
  620. def clean(self, value):
  621. """
  622. Validates the given value against all of self.fields, which is a
  623. list of Field instances.
  624. """
  625. super(ComboField, self).clean(value)
  626. for field in self.fields:
  627. value = field.clean(value)
  628. return value
  629. class MultiValueField(Field):
  630. """
  631. A Field that aggregates the logic of multiple Fields.
  632. Its clean() method takes a "decompressed" list of values, which are then
  633. cleaned into a single value according to self.fields. Each value in
  634. this list is cleaned by the corresponding field -- the first value is
  635. cleaned by the first field, the second value is cleaned by the second
  636. field, etc. Once all fields are cleaned, the list of clean values is
  637. "compressed" into a single value.
  638. Subclasses should not have to implement clean(). Instead, they must
  639. implement compress(), which takes a list of valid values and returns a
  640. "compressed" version of those values -- a single value.
  641. You'll probably want to use this with MultiWidget.
  642. """
  643. default_error_messages = {
  644. 'invalid': _(u'Enter a list of values.'),
  645. }
  646. def __init__(self, fields=(), *args, **kwargs):
  647. super(MultiValueField, self).__init__(*args, **kwargs)
  648. # Set 'required' to False on the individual fields, because the
  649. # required validation will be handled by MultiValueField, not by those
  650. # individual fields.
  651. for f in fields:
  652. f.required = False
  653. self.fields = fields
  654. def validate(self, value):
  655. pass
  656. def clean(self, value):
  657. """
  658. Validates every value in the given list. A value is validated against
  659. the corresponding Field in self.fields.
  660. For example, if this MultiValueField was instantiated with
  661. fields=(DateField(), TimeField()), clean() would call
  662. DateField.clean(value[0]) and TimeField.clean(value[1]).
  663. """
  664. clean_data = []
  665. errors = ErrorList()
  666. if not value or isinstance(value, (list, tuple)):
  667. if not value or not [v for v in value if v not in validators.EMPTY_VALUES]:
  668. if self.required:
  669. raise ValidationError(self.error_messages['required'])
  670. else:
  671. return self.compress([])
  672. else:
  673. raise ValidationError(self.error_messages['invalid'])
  674. for i, field in enumerate(self.fields):
  675. try:
  676. field_value = value[i]
  677. except IndexError:
  678. field_value = None
  679. if self.required and field_value in validators.EMPTY_VALUES:
  680. raise ValidationError(self.error_messages['required'])
  681. try:
  682. clean_data.append(field.clean(field_value))
  683. except ValidationError, e:
  684. # Collect all validation errors in a single list, which we'll
  685. # raise at the end of clean(), rather than raising a single
  686. # exception for the first error we encounter.
  687. errors.extend(e.messages)
  688. if errors:
  689. raise ValidationError(errors)
  690. out = self.compress(clean_data)
  691. self.validate(out)
  692. return out
  693. def compress(self, data_list):
  694. """
  695. Returns a single value for the given list of values. The values can be
  696. assumed to be valid.
  697. For example, if this MultiValueField was instantiated with
  698. fields=(DateField(), TimeField()), this might return a datetime
  699. object created by combining the date and time in data_list.
  700. """
  701. raise NotImplementedError('Subclasses must implement this method.')
  702. class FilePathField(ChoiceField):
  703. def __init__(self, path, match=None, recursive=False, required=True,
  704. widget=None, label=None, initial=None, help_text=None,
  705. *args, **kwargs):
  706. self.path, self.match, self.recursive = path, match, recursive
  707. super(FilePathField, self).__init__(choices=(), required=required,
  708. widget=widget, label=label, initial=initial, help_text=help_text,
  709. *args, **kwargs)
  710. if self.required:
  711. self.choices = []
  712. else:
  713. self.choices = [("", "---------")]
  714. if self.match is not None:
  715. self.match_re = re.compile(self.match)
  716. if recursive:
  717. for root, dirs, files in os.walk(self.path):
  718. for f in files:
  719. if self.match is None or self.match_re.search(f):
  720. f = os.path.join(root, f)
  721. self.choices.append((f, f.replace(path, "", 1)))
  722. else:
  723. try:
  724. for f in os.listdir(self.path):
  725. full_file = os.path.join(self.path, f)
  726. if os.path.isfile(full_file) and (self.match is None or self.match_re.search(f)):
  727. self.choices.append((full_file, f))
  728. except OSError:
  729. pass
  730. self.widget.choices = self.choices
  731. class SplitDateTimeField(MultiValueField):
  732. widget = SplitDateTimeWidget
  733. hidden_widget = SplitHiddenDateTimeWidget
  734. default_error_messages = {
  735. 'invalid_date': _(u'Enter a valid date.'),
  736. 'invalid_time': _(u'Enter a valid time.'),
  737. }
  738. def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
  739. errors = self.default_error_messages.copy()
  740. if 'error_messages' in kwargs:
  741. errors.update(kwargs['error_messages'])
  742. localize = kwargs.get('localize', False)
  743. fields = (
  744. DateField(input_formats=input_date_formats,
  745. error_messages={'invalid': errors['invalid_date']},
  746. localize=localize),
  747. TimeField(input_formats=input_time_formats,
  748. error_messages={'invalid': errors['invalid_time']},
  749. localize=localize),
  750. )
  751. super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
  752. def compress(self, data_list):
  753. if data_list:
  754. # Raise a validation error if time or date is empty
  755. # (possible if SplitDateTimeField has required=False).
  756. if data_list[0] in validators.EMPTY_VALUES:
  757. raise ValidationError(self.error_messages['invalid_date'])
  758. if data_list[1] in validators.EMPTY_VALUES:
  759. raise ValidationError(self.error_messages['invalid_time'])
  760. return datetime.datetime.combine(*data_list)
  761. return None
  762. class IPAddressField(CharField):
  763. default_error_messages = {
  764. 'invalid': _(u'Enter a valid IPv4 address.'),
  765. }
  766. default_validators = [validators.validate_ipv4_address]
  767. class SlugField(CharField):
  768. default_error_messages = {
  769. 'invalid': _(u"Enter a valid 'slug' consisting of letters, numbers,"
  770. u" underscores or hyphens."),
  771. }
  772. default_validators = [validators.validate_slug]