PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/django/forms/fields.py

https://github.com/andnils/django
Python | 1202 lines | 1160 code | 22 blank | 20 comment | 18 complexity | 9f7dbdad20a111279ba38f2637416772 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Field classes.
  3. """
  4. from __future__ import unicode_literals
  5. import copy
  6. import datetime
  7. import os
  8. import re
  9. import sys
  10. import warnings
  11. from decimal import Decimal, DecimalException
  12. from io import BytesIO
  13. from django.core import validators
  14. from django.core.exceptions import ValidationError
  15. from django.forms.utils import from_current_timezone, to_current_timezone
  16. from django.forms.widgets import (
  17. TextInput, NumberInput, EmailInput, URLInput, HiddenInput,
  18. MultipleHiddenInput, ClearableFileInput, CheckboxInput, Select,
  19. NullBooleanSelect, SelectMultiple, DateInput, DateTimeInput, TimeInput,
  20. SplitDateTimeWidget, SplitHiddenDateTimeWidget, FILE_INPUT_CONTRADICTION
  21. )
  22. from django.utils import formats
  23. from django.utils.encoding import smart_text, force_str, force_text
  24. from django.utils.ipv6 import clean_ipv6_address
  25. from django.utils.deprecation import RemovedInDjango19Warning
  26. from django.utils import six
  27. from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
  28. from django.utils.translation import ugettext_lazy as _, ungettext_lazy
  29. # Provide this import for backwards compatibility.
  30. from django.core.validators import EMPTY_VALUES # NOQA
  31. __all__ = (
  32. 'Field', 'CharField', 'IntegerField',
  33. 'DateField', 'TimeField', 'DateTimeField',
  34. 'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
  35. 'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
  36. 'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
  37. 'SplitDateTimeField', 'IPAddressField', 'GenericIPAddressField', 'FilePathField',
  38. 'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField'
  39. )
  40. class Field(object):
  41. widget = TextInput # Default widget to use when rendering this type of Field.
  42. hidden_widget = HiddenInput # Default widget to use when rendering this as "hidden".
  43. default_validators = [] # Default set of validators
  44. # Add an 'invalid' entry to default_error_message if you want a specific
  45. # field error message not raised by the field validators.
  46. default_error_messages = {
  47. 'required': _('This field is required.'),
  48. }
  49. empty_values = list(validators.EMPTY_VALUES)
  50. # Tracks each time a Field instance is created. Used to retain order.
  51. creation_counter = 0
  52. def __init__(self, required=True, widget=None, label=None, initial=None,
  53. help_text='', error_messages=None, show_hidden_initial=False,
  54. validators=[], localize=False):
  55. # required -- Boolean that specifies whether the field is required.
  56. # True by default.
  57. # widget -- A Widget class, or instance of a Widget class, that should
  58. # be used for this Field when displaying it. Each Field has a
  59. # default Widget that it'll use if you don't specify this. In
  60. # most cases, the default widget is TextInput.
  61. # label -- A verbose name for this field, for use in displaying this
  62. # field in a form. By default, Django will use a "pretty"
  63. # version of the form field name, if the Field is part of a
  64. # Form.
  65. # initial -- A value to use in this Field's initial display. This value
  66. # is *not* used as a fallback if data isn't given.
  67. # help_text -- An optional string to use as "help text" for this Field.
  68. # error_messages -- An optional dictionary to override the default
  69. # messages that the field will raise.
  70. # show_hidden_initial -- Boolean that specifies if it is needed to render a
  71. # hidden widget with initial value after widget.
  72. # validators -- List of addtional validators to use
  73. # localize -- Boolean that specifies if the field should be localized.
  74. self.required, self.label, self.initial = required, label, initial
  75. self.show_hidden_initial = show_hidden_initial
  76. self.help_text = help_text
  77. widget = widget or self.widget
  78. if isinstance(widget, type):
  79. widget = widget()
  80. # Trigger the localization machinery if needed.
  81. self.localize = localize
  82. if self.localize:
  83. widget.is_localized = True
  84. # Let the widget know whether it should display as required.
  85. widget.is_required = self.required
  86. # Hook into self.widget_attrs() for any Field-specific HTML attributes.
  87. extra_attrs = self.widget_attrs(widget)
  88. if extra_attrs:
  89. widget.attrs.update(extra_attrs)
  90. self.widget = widget
  91. # Increase the creation counter, and save our local copy.
  92. self.creation_counter = Field.creation_counter
  93. Field.creation_counter += 1
  94. messages = {}
  95. for c in reversed(self.__class__.__mro__):
  96. messages.update(getattr(c, 'default_error_messages', {}))
  97. messages.update(error_messages or {})
  98. self.error_messages = messages
  99. self.validators = self.default_validators + validators
  100. super(Field, self).__init__()
  101. def prepare_value(self, value):
  102. return value
  103. def to_python(self, value):
  104. return value
  105. def validate(self, value):
  106. if value in self.empty_values and self.required:
  107. raise ValidationError(self.error_messages['required'], code='required')
  108. def run_validators(self, value):
  109. if value in self.empty_values:
  110. return
  111. errors = []
  112. for v in self.validators:
  113. try:
  114. v(value)
  115. except ValidationError as e:
  116. if hasattr(e, 'code') and e.code in self.error_messages:
  117. e.message = self.error_messages[e.code]
  118. errors.extend(e.error_list)
  119. if errors:
  120. raise ValidationError(errors)
  121. def clean(self, value):
  122. """
  123. Validates the given value and returns its "cleaned" value as an
  124. appropriate Python object.
  125. Raises ValidationError for any errors.
  126. """
  127. value = self.to_python(value)
  128. self.validate(value)
  129. self.run_validators(value)
  130. return value
  131. def bound_data(self, data, initial):
  132. """
  133. Return the value that should be shown for this field on render of a
  134. bound form, given the submitted POST data for the field and the initial
  135. data, if any.
  136. For most fields, this will simply be data; FileFields need to handle it
  137. a bit differently.
  138. """
  139. return data
  140. def widget_attrs(self, widget):
  141. """
  142. Given a Widget instance (*not* a Widget class), returns a dictionary of
  143. any HTML attributes that should be added to the Widget, based on this
  144. Field.
  145. """
  146. return {}
  147. def get_limit_choices_to(self):
  148. """
  149. Returns ``limit_choices_to`` for this form field.
  150. If it is a callable, it will be invoked and the result will be
  151. returned.
  152. """
  153. if callable(self.limit_choices_to):
  154. return self.limit_choices_to()
  155. return self.limit_choices_to
  156. def _has_changed(self, initial, data):
  157. """
  158. Return True if data differs from initial.
  159. """
  160. # For purposes of seeing whether something has changed, None is
  161. # the same as an empty string, if the data or inital value we get
  162. # is None, replace it w/ ''.
  163. initial_value = initial if initial is not None else ''
  164. try:
  165. data = self.to_python(data)
  166. if hasattr(self, '_coerce'):
  167. data = self._coerce(data)
  168. except ValidationError:
  169. return True
  170. data_value = data if data is not None else ''
  171. return initial_value != data_value
  172. def __deepcopy__(self, memo):
  173. result = copy.copy(self)
  174. memo[id(self)] = result
  175. result.widget = copy.deepcopy(self.widget, memo)
  176. result.validators = self.validators[:]
  177. return result
  178. class CharField(Field):
  179. def __init__(self, max_length=None, min_length=None, *args, **kwargs):
  180. self.max_length, self.min_length = max_length, min_length
  181. super(CharField, self).__init__(*args, **kwargs)
  182. if min_length is not None:
  183. self.validators.append(validators.MinLengthValidator(int(min_length)))
  184. if max_length is not None:
  185. self.validators.append(validators.MaxLengthValidator(int(max_length)))
  186. def to_python(self, value):
  187. "Returns a Unicode object."
  188. if value in self.empty_values:
  189. return ''
  190. return smart_text(value)
  191. def widget_attrs(self, widget):
  192. attrs = super(CharField, self).widget_attrs(widget)
  193. if self.max_length is not None:
  194. # The HTML attribute is maxlength, not max_length.
  195. attrs.update({'maxlength': str(self.max_length)})
  196. return attrs
  197. class IntegerField(Field):
  198. widget = NumberInput
  199. default_error_messages = {
  200. 'invalid': _('Enter a whole number.'),
  201. }
  202. def __init__(self, max_value=None, min_value=None, *args, **kwargs):
  203. self.max_value, self.min_value = max_value, min_value
  204. if kwargs.get('localize') and self.widget == NumberInput:
  205. # Localized number input is not well supported on most browsers
  206. kwargs.setdefault('widget', super(IntegerField, self).widget)
  207. super(IntegerField, self).__init__(*args, **kwargs)
  208. if max_value is not None:
  209. self.validators.append(validators.MaxValueValidator(max_value))
  210. if min_value is not None:
  211. self.validators.append(validators.MinValueValidator(min_value))
  212. def to_python(self, value):
  213. """
  214. Validates that int() can be called on the input. Returns the result
  215. of int(). Returns None for empty values.
  216. """
  217. value = super(IntegerField, self).to_python(value)
  218. if value in self.empty_values:
  219. return None
  220. if self.localize:
  221. value = formats.sanitize_separators(value)
  222. try:
  223. value = int(str(value))
  224. except (ValueError, TypeError):
  225. raise ValidationError(self.error_messages['invalid'], code='invalid')
  226. return value
  227. def widget_attrs(self, widget):
  228. attrs = super(IntegerField, self).widget_attrs(widget)
  229. if isinstance(widget, NumberInput):
  230. if self.min_value is not None:
  231. attrs['min'] = self.min_value
  232. if self.max_value is not None:
  233. attrs['max'] = self.max_value
  234. return attrs
  235. class FloatField(IntegerField):
  236. default_error_messages = {
  237. 'invalid': _('Enter a number.'),
  238. }
  239. def to_python(self, value):
  240. """
  241. Validates that float() can be called on the input. Returns the result
  242. of float(). Returns None for empty values.
  243. """
  244. value = super(IntegerField, self).to_python(value)
  245. if value in self.empty_values:
  246. return None
  247. if self.localize:
  248. value = formats.sanitize_separators(value)
  249. try:
  250. value = float(value)
  251. except (ValueError, TypeError):
  252. raise ValidationError(self.error_messages['invalid'], code='invalid')
  253. return value
  254. def validate(self, value):
  255. super(FloatField, self).validate(value)
  256. # Check for NaN (which is the only thing not equal to itself) and +/- infinity
  257. if value != value or value in (Decimal('Inf'), Decimal('-Inf')):
  258. raise ValidationError(self.error_messages['invalid'], code='invalid')
  259. return value
  260. def widget_attrs(self, widget):
  261. attrs = super(FloatField, self).widget_attrs(widget)
  262. if isinstance(widget, NumberInput) and 'step' not in widget.attrs:
  263. attrs.setdefault('step', 'any')
  264. return attrs
  265. class DecimalField(IntegerField):
  266. default_error_messages = {
  267. 'invalid': _('Enter a number.'),
  268. 'max_digits': ungettext_lazy(
  269. 'Ensure that there are no more than %(max)s digit in total.',
  270. 'Ensure that there are no more than %(max)s digits in total.',
  271. 'max'),
  272. 'max_decimal_places': ungettext_lazy(
  273. 'Ensure that there are no more than %(max)s decimal place.',
  274. 'Ensure that there are no more than %(max)s decimal places.',
  275. 'max'),
  276. 'max_whole_digits': ungettext_lazy(
  277. 'Ensure that there are no more than %(max)s digit before the decimal point.',
  278. 'Ensure that there are no more than %(max)s digits before the decimal point.',
  279. 'max'),
  280. }
  281. def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
  282. self.max_digits, self.decimal_places = max_digits, decimal_places
  283. super(DecimalField, self).__init__(max_value, min_value, *args, **kwargs)
  284. def to_python(self, value):
  285. """
  286. Validates that the input is a decimal number. Returns a Decimal
  287. instance. Returns None for empty values. Ensures that there are no more
  288. than max_digits in the number, and no more than decimal_places digits
  289. after the decimal point.
  290. """
  291. if value in self.empty_values:
  292. return None
  293. if self.localize:
  294. value = formats.sanitize_separators(value)
  295. value = smart_text(value).strip()
  296. try:
  297. value = Decimal(value)
  298. except DecimalException:
  299. raise ValidationError(self.error_messages['invalid'], code='invalid')
  300. return value
  301. def validate(self, value):
  302. super(DecimalField, self).validate(value)
  303. if value in self.empty_values:
  304. return
  305. # Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
  306. # since it is never equal to itself. However, NaN is the only value that
  307. # isn't equal to itself, so we can use this to identify NaN
  308. if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
  309. raise ValidationError(self.error_messages['invalid'], code='invalid')
  310. sign, digittuple, exponent = value.as_tuple()
  311. decimals = abs(exponent)
  312. # digittuple doesn't include any leading zeros.
  313. digits = len(digittuple)
  314. if decimals > digits:
  315. # We have leading zeros up to or past the decimal point. Count
  316. # everything past the decimal point as a digit. We do not count
  317. # 0 before the decimal point as a digit since that would mean
  318. # we would not allow max_digits = decimal_places.
  319. digits = decimals
  320. whole_digits = digits - decimals
  321. if self.max_digits is not None and digits > self.max_digits:
  322. raise ValidationError(
  323. self.error_messages['max_digits'],
  324. code='max_digits',
  325. params={'max': self.max_digits},
  326. )
  327. if self.decimal_places is not None and decimals > self.decimal_places:
  328. raise ValidationError(
  329. self.error_messages['max_decimal_places'],
  330. code='max_decimal_places',
  331. params={'max': self.decimal_places},
  332. )
  333. if (self.max_digits is not None and self.decimal_places is not None
  334. and whole_digits > (self.max_digits - self.decimal_places)):
  335. raise ValidationError(
  336. self.error_messages['max_whole_digits'],
  337. code='max_whole_digits',
  338. params={'max': (self.max_digits - self.decimal_places)},
  339. )
  340. return value
  341. def widget_attrs(self, widget):
  342. attrs = super(DecimalField, self).widget_attrs(widget)
  343. if isinstance(widget, NumberInput) and 'step' not in widget.attrs:
  344. if self.decimal_places is not None:
  345. # Use exponential notation for small values since they might
  346. # be parsed as 0 otherwise. ref #20765
  347. step = str(Decimal('1') / 10 ** self.decimal_places).lower()
  348. else:
  349. step = 'any'
  350. attrs.setdefault('step', step)
  351. return attrs
  352. class BaseTemporalField(Field):
  353. def __init__(self, input_formats=None, *args, **kwargs):
  354. super(BaseTemporalField, self).__init__(*args, **kwargs)
  355. if input_formats is not None:
  356. self.input_formats = input_formats
  357. def to_python(self, value):
  358. # Try to coerce the value to unicode.
  359. unicode_value = force_text(value, strings_only=True)
  360. if isinstance(unicode_value, six.text_type):
  361. value = unicode_value.strip()
  362. # If unicode, try to strptime against each input format.
  363. if isinstance(value, six.text_type):
  364. for format in self.input_formats:
  365. try:
  366. return self.strptime(value, format)
  367. except (ValueError, TypeError):
  368. continue
  369. raise ValidationError(self.error_messages['invalid'], code='invalid')
  370. def strptime(self, value, format):
  371. raise NotImplementedError('Subclasses must define this method.')
  372. class DateField(BaseTemporalField):
  373. widget = DateInput
  374. input_formats = formats.get_format_lazy('DATE_INPUT_FORMATS')
  375. default_error_messages = {
  376. 'invalid': _('Enter a valid date.'),
  377. }
  378. def to_python(self, value):
  379. """
  380. Validates that the input can be converted to a date. Returns a Python
  381. datetime.date object.
  382. """
  383. if value in self.empty_values:
  384. return None
  385. if isinstance(value, datetime.datetime):
  386. return value.date()
  387. if isinstance(value, datetime.date):
  388. return value
  389. return super(DateField, self).to_python(value)
  390. def strptime(self, value, format):
  391. return datetime.datetime.strptime(force_str(value), format).date()
  392. class TimeField(BaseTemporalField):
  393. widget = TimeInput
  394. input_formats = formats.get_format_lazy('TIME_INPUT_FORMATS')
  395. default_error_messages = {
  396. 'invalid': _('Enter a valid time.')
  397. }
  398. def to_python(self, value):
  399. """
  400. Validates that the input can be converted to a time. Returns a Python
  401. datetime.time object.
  402. """
  403. if value in self.empty_values:
  404. return None
  405. if isinstance(value, datetime.time):
  406. return value
  407. return super(TimeField, self).to_python(value)
  408. def strptime(self, value, format):
  409. return datetime.datetime.strptime(force_str(value), format).time()
  410. class DateTimeField(BaseTemporalField):
  411. widget = DateTimeInput
  412. input_formats = formats.get_format_lazy('DATETIME_INPUT_FORMATS')
  413. default_error_messages = {
  414. 'invalid': _('Enter a valid date/time.'),
  415. }
  416. def prepare_value(self, value):
  417. if isinstance(value, datetime.datetime):
  418. value = to_current_timezone(value)
  419. return value
  420. def to_python(self, value):
  421. """
  422. Validates that the input can be converted to a datetime. Returns a
  423. Python datetime.datetime object.
  424. """
  425. if value in self.empty_values:
  426. return None
  427. if isinstance(value, datetime.datetime):
  428. return from_current_timezone(value)
  429. if isinstance(value, datetime.date):
  430. result = datetime.datetime(value.year, value.month, value.day)
  431. return from_current_timezone(result)
  432. if isinstance(value, list):
  433. # Input comes from a SplitDateTimeWidget, for example. So, it's two
  434. # components: date and time.
  435. warnings.warn(
  436. 'Using SplitDateTimeWidget with DateTimeField is deprecated. '
  437. 'Use SplitDateTimeField instead.',
  438. RemovedInDjango19Warning, stacklevel=2)
  439. if len(value) != 2:
  440. raise ValidationError(self.error_messages['invalid'], code='invalid')
  441. if value[0] in self.empty_values and value[1] in self.empty_values:
  442. return None
  443. value = '%s %s' % tuple(value)
  444. result = super(DateTimeField, self).to_python(value)
  445. return from_current_timezone(result)
  446. def strptime(self, value, format):
  447. return datetime.datetime.strptime(force_str(value), format)
  448. class RegexField(CharField):
  449. def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
  450. """
  451. regex can be either a string or a compiled regular expression object.
  452. error_message is an optional error message to use, if
  453. 'Enter a valid value' is too generic for you.
  454. """
  455. # error_message is just kept for backwards compatibility:
  456. if error_message:
  457. error_messages = kwargs.get('error_messages') or {}
  458. error_messages['invalid'] = error_message
  459. kwargs['error_messages'] = error_messages
  460. super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
  461. self._set_regex(regex)
  462. def _get_regex(self):
  463. return self._regex
  464. def _set_regex(self, regex):
  465. if isinstance(regex, six.string_types):
  466. regex = re.compile(regex, re.UNICODE)
  467. self._regex = regex
  468. if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
  469. self.validators.remove(self._regex_validator)
  470. self._regex_validator = validators.RegexValidator(regex=regex)
  471. self.validators.append(self._regex_validator)
  472. regex = property(_get_regex, _set_regex)
  473. class EmailField(CharField):
  474. widget = EmailInput
  475. default_validators = [validators.validate_email]
  476. def clean(self, value):
  477. value = self.to_python(value).strip()
  478. return super(EmailField, self).clean(value)
  479. class FileField(Field):
  480. widget = ClearableFileInput
  481. default_error_messages = {
  482. 'invalid': _("No file was submitted. Check the encoding type on the form."),
  483. 'missing': _("No file was submitted."),
  484. 'empty': _("The submitted file is empty."),
  485. 'max_length': ungettext_lazy(
  486. 'Ensure this filename has at most %(max)d character (it has %(length)d).',
  487. 'Ensure this filename has at most %(max)d characters (it has %(length)d).',
  488. 'max'),
  489. 'contradiction': _('Please either submit a file or check the clear checkbox, not both.')
  490. }
  491. def __init__(self, *args, **kwargs):
  492. self.max_length = kwargs.pop('max_length', None)
  493. self.allow_empty_file = kwargs.pop('allow_empty_file', False)
  494. super(FileField, self).__init__(*args, **kwargs)
  495. def to_python(self, data):
  496. if data in self.empty_values:
  497. return None
  498. # UploadedFile objects should have name and size attributes.
  499. try:
  500. file_name = data.name
  501. file_size = data.size
  502. except AttributeError:
  503. raise ValidationError(self.error_messages['invalid'], code='invalid')
  504. if self.max_length is not None and len(file_name) > self.max_length:
  505. params = {'max': self.max_length, 'length': len(file_name)}
  506. raise ValidationError(self.error_messages['max_length'], code='max_length', params=params)
  507. if not file_name:
  508. raise ValidationError(self.error_messages['invalid'], code='invalid')
  509. if not self.allow_empty_file and not file_size:
  510. raise ValidationError(self.error_messages['empty'], code='empty')
  511. return data
  512. def clean(self, data, initial=None):
  513. # If the widget got contradictory inputs, we raise a validation error
  514. if data is FILE_INPUT_CONTRADICTION:
  515. raise ValidationError(self.error_messages['contradiction'], code='contradiction')
  516. # False means the field value should be cleared; further validation is
  517. # not needed.
  518. if data is False:
  519. if not self.required:
  520. return False
  521. # If the field is required, clearing is not possible (the widget
  522. # shouldn't return False data in that case anyway). False is not
  523. # in self.empty_value; if a False value makes it this far
  524. # it should be validated from here on out as None (so it will be
  525. # caught by the required check).
  526. data = None
  527. if not data and initial:
  528. return initial
  529. return super(FileField, self).clean(data)
  530. def bound_data(self, data, initial):
  531. if data in (None, FILE_INPUT_CONTRADICTION):
  532. return initial
  533. return data
  534. def _has_changed(self, initial, data):
  535. if data is None:
  536. return False
  537. return True
  538. class ImageField(FileField):
  539. default_error_messages = {
  540. 'invalid_image': _("Upload a valid image. The file you uploaded was either not an image or a corrupted image."),
  541. }
  542. def to_python(self, data):
  543. """
  544. Checks that the file-upload field data contains a valid image (GIF, JPG,
  545. PNG, possibly others -- whatever the Python Imaging Library supports).
  546. """
  547. f = super(ImageField, self).to_python(data)
  548. if f is None:
  549. return None
  550. from PIL import Image
  551. # We need to get a file object for Pillow. We might have a path or we might
  552. # have to read the data into memory.
  553. if hasattr(data, 'temporary_file_path'):
  554. file = data.temporary_file_path()
  555. else:
  556. if hasattr(data, 'read'):
  557. file = BytesIO(data.read())
  558. else:
  559. file = BytesIO(data['content'])
  560. try:
  561. # load() could spot a truncated JPEG, but it loads the entire
  562. # image in memory, which is a DoS vector. See #3848 and #18520.
  563. # verify() must be called immediately after the constructor.
  564. Image.open(file).verify()
  565. except Exception:
  566. # Pillow doesn't recognize it as an image.
  567. six.reraise(ValidationError, ValidationError(
  568. self.error_messages['invalid_image'],
  569. code='invalid_image',
  570. ), sys.exc_info()[2])
  571. if hasattr(f, 'seek') and callable(f.seek):
  572. f.seek(0)
  573. return f
  574. class URLField(CharField):
  575. widget = URLInput
  576. default_error_messages = {
  577. 'invalid': _('Enter a valid URL.'),
  578. }
  579. default_validators = [validators.URLValidator()]
  580. def to_python(self, value):
  581. def split_url(url):
  582. """
  583. Returns a list of url parts via ``urlparse.urlsplit`` (or raises a
  584. ``ValidationError`` exception for certain).
  585. """
  586. try:
  587. return list(urlsplit(url))
  588. except ValueError:
  589. # urlparse.urlsplit can raise a ValueError with some
  590. # misformatted URLs.
  591. raise ValidationError(self.error_messages['invalid'], code='invalid')
  592. value = super(URLField, self).to_python(value)
  593. if value:
  594. url_fields = split_url(value)
  595. if not url_fields[0]:
  596. # If no URL scheme given, assume http://
  597. url_fields[0] = 'http'
  598. if not url_fields[1]:
  599. # Assume that if no domain is provided, that the path segment
  600. # contains the domain.
  601. url_fields[1] = url_fields[2]
  602. url_fields[2] = ''
  603. # Rebuild the url_fields list, since the domain segment may now
  604. # contain the path too.
  605. url_fields = split_url(urlunsplit(url_fields))
  606. value = urlunsplit(url_fields)
  607. return value
  608. def clean(self, value):
  609. value = self.to_python(value).strip()
  610. return super(URLField, self).clean(value)
  611. class BooleanField(Field):
  612. widget = CheckboxInput
  613. def to_python(self, value):
  614. """Returns a Python boolean object."""
  615. # Explicitly check for the string 'False', which is what a hidden field
  616. # will submit for False. Also check for '0', since this is what
  617. # RadioSelect will provide. Because bool("True") == bool('1') == True,
  618. # we don't need to handle that explicitly.
  619. if isinstance(value, six.string_types) and value.lower() in ('false', '0'):
  620. value = False
  621. else:
  622. value = bool(value)
  623. return super(BooleanField, self).to_python(value)
  624. def validate(self, value):
  625. if not value and self.required:
  626. raise ValidationError(self.error_messages['required'], code='required')
  627. def _has_changed(self, initial, data):
  628. # Sometimes data or initial could be None or '' which should be the
  629. # same thing as False.
  630. if initial == 'False':
  631. # show_hidden_initial may have transformed False to 'False'
  632. initial = False
  633. return bool(initial) != bool(data)
  634. class NullBooleanField(BooleanField):
  635. """
  636. A field whose valid values are None, True and False. Invalid values are
  637. cleaned to None.
  638. """
  639. widget = NullBooleanSelect
  640. def to_python(self, value):
  641. """
  642. Explicitly checks for the string 'True' and 'False', which is what a
  643. hidden field will submit for True and False, and for '1' and '0', which
  644. is what a RadioField will submit. Unlike the Booleanfield we need to
  645. explicitly check for True, because we are not using the bool() function
  646. """
  647. if value in (True, 'True', '1'):
  648. return True
  649. elif value in (False, 'False', '0'):
  650. return False
  651. else:
  652. return None
  653. def validate(self, value):
  654. pass
  655. def _has_changed(self, initial, data):
  656. # None (unknown) and False (No) are not the same
  657. if initial is not None:
  658. initial = bool(initial)
  659. if data is not None:
  660. data = bool(data)
  661. return initial != data
  662. class ChoiceField(Field):
  663. widget = Select
  664. default_error_messages = {
  665. 'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
  666. }
  667. def __init__(self, choices=(), required=True, widget=None, label=None,
  668. initial=None, help_text='', *args, **kwargs):
  669. super(ChoiceField, self).__init__(required=required, widget=widget, label=label,
  670. initial=initial, help_text=help_text, *args, **kwargs)
  671. self.choices = choices
  672. def __deepcopy__(self, memo):
  673. result = super(ChoiceField, self).__deepcopy__(memo)
  674. result._choices = copy.deepcopy(self._choices, memo)
  675. return result
  676. def _get_choices(self):
  677. return self._choices
  678. def _set_choices(self, value):
  679. # Setting choices also sets the choices on the widget.
  680. # choices can be any iterable, but we call list() on it because
  681. # it will be consumed more than once.
  682. self._choices = self.widget.choices = list(value)
  683. choices = property(_get_choices, _set_choices)
  684. def to_python(self, value):
  685. "Returns a Unicode object."
  686. if value in self.empty_values:
  687. return ''
  688. return smart_text(value)
  689. def validate(self, value):
  690. """
  691. Validates that the input is in self.choices.
  692. """
  693. super(ChoiceField, self).validate(value)
  694. if value and not self.valid_value(value):
  695. raise ValidationError(
  696. self.error_messages['invalid_choice'],
  697. code='invalid_choice',
  698. params={'value': value},
  699. )
  700. def valid_value(self, value):
  701. "Check to see if the provided value is a valid choice"
  702. text_value = force_text(value)
  703. for k, v in self.choices:
  704. if isinstance(v, (list, tuple)):
  705. # This is an optgroup, so look inside the group for options
  706. for k2, v2 in v:
  707. if value == k2 or text_value == force_text(k2):
  708. return True
  709. else:
  710. if value == k or text_value == force_text(k):
  711. return True
  712. return False
  713. class TypedChoiceField(ChoiceField):
  714. def __init__(self, *args, **kwargs):
  715. self.coerce = kwargs.pop('coerce', lambda val: val)
  716. self.empty_value = kwargs.pop('empty_value', '')
  717. super(TypedChoiceField, self).__init__(*args, **kwargs)
  718. def _coerce(self, value):
  719. """
  720. Validate that the value can be coerced to the right type (if not empty).
  721. """
  722. if value == self.empty_value or value in self.empty_values:
  723. return self.empty_value
  724. try:
  725. value = self.coerce(value)
  726. except (ValueError, TypeError, ValidationError):
  727. raise ValidationError(
  728. self.error_messages['invalid_choice'],
  729. code='invalid_choice',
  730. params={'value': value},
  731. )
  732. return value
  733. def clean(self, value):
  734. value = super(TypedChoiceField, self).clean(value)
  735. return self._coerce(value)
  736. class MultipleChoiceField(ChoiceField):
  737. hidden_widget = MultipleHiddenInput
  738. widget = SelectMultiple
  739. default_error_messages = {
  740. 'invalid_choice': _('Select a valid choice. %(value)s is not one of the available choices.'),
  741. 'invalid_list': _('Enter a list of values.'),
  742. }
  743. def to_python(self, value):
  744. if not value:
  745. return []
  746. elif not isinstance(value, (list, tuple)):
  747. raise ValidationError(self.error_messages['invalid_list'], code='invalid_list')
  748. return [smart_text(val) for val in value]
  749. def validate(self, value):
  750. """
  751. Validates that the input is a list or tuple.
  752. """
  753. if self.required and not value:
  754. raise ValidationError(self.error_messages['required'], code='required')
  755. # Validate that each value in the value list is in self.choices.
  756. for val in value:
  757. if not self.valid_value(val):
  758. raise ValidationError(
  759. self.error_messages['invalid_choice'],
  760. code='invalid_choice',
  761. params={'value': val},
  762. )
  763. def _has_changed(self, initial, data):
  764. if initial is None:
  765. initial = []
  766. if data is None:
  767. data = []
  768. if len(initial) != len(data):
  769. return True
  770. initial_set = set(force_text(value) for value in initial)
  771. data_set = set(force_text(value) for value in data)
  772. return data_set != initial_set
  773. class TypedMultipleChoiceField(MultipleChoiceField):
  774. def __init__(self, *args, **kwargs):
  775. self.coerce = kwargs.pop('coerce', lambda val: val)
  776. self.empty_value = kwargs.pop('empty_value', [])
  777. super(TypedMultipleChoiceField, self).__init__(*args, **kwargs)
  778. def _coerce(self, value):
  779. """
  780. Validates that the values are in self.choices and can be coerced to the
  781. right type.
  782. """
  783. if value == self.empty_value or value in self.empty_values:
  784. return self.empty_value
  785. new_value = []
  786. for choice in value:
  787. try:
  788. new_value.append(self.coerce(choice))
  789. except (ValueError, TypeError, ValidationError):
  790. raise ValidationError(
  791. self.error_messages['invalid_choice'],
  792. code='invalid_choice',
  793. params={'value': choice},
  794. )
  795. return new_value
  796. def clean(self, value):
  797. value = super(TypedMultipleChoiceField, self).clean(value)
  798. return self._coerce(value)
  799. def validate(self, value):
  800. if value != self.empty_value:
  801. super(TypedMultipleChoiceField, self).validate(value)
  802. elif self.required:
  803. raise ValidationError(self.error_messages['required'], code='required')
  804. class ComboField(Field):
  805. """
  806. A Field whose clean() method calls multiple Field clean() methods.
  807. """
  808. def __init__(self, fields=(), *args, **kwargs):
  809. super(ComboField, self).__init__(*args, **kwargs)
  810. # Set 'required' to False on the individual fields, because the
  811. # required validation will be handled by ComboField, not by those
  812. # individual fields.
  813. for f in fields:
  814. f.required = False
  815. self.fields = fields
  816. def clean(self, value):
  817. """
  818. Validates the given value against all of self.fields, which is a
  819. list of Field instances.
  820. """
  821. super(ComboField, self).clean(value)
  822. for field in self.fields:
  823. value = field.clean(value)
  824. return value
  825. class MultiValueField(Field):
  826. """
  827. A Field that aggregates the logic of multiple Fields.
  828. Its clean() method takes a "decompressed" list of values, which are then
  829. cleaned into a single value according to self.fields. Each value in
  830. this list is cleaned by the corresponding field -- the first value is
  831. cleaned by the first field, the second value is cleaned by the second
  832. field, etc. Once all fields are cleaned, the list of clean values is
  833. "compressed" into a single value.
  834. Subclasses should not have to implement clean(). Instead, they must
  835. implement compress(), which takes a list of valid values and returns a
  836. "compressed" version of those values -- a single value.
  837. You'll probably want to use this with MultiWidget.
  838. """
  839. default_error_messages = {
  840. 'invalid': _('Enter a list of values.'),
  841. 'incomplete': _('Enter a complete value.'),
  842. }
  843. def __init__(self, fields=(), *args, **kwargs):
  844. self.require_all_fields = kwargs.pop('require_all_fields', True)
  845. super(MultiValueField, self).__init__(*args, **kwargs)
  846. for f in fields:
  847. f.error_messages.setdefault('incomplete',
  848. self.error_messages['incomplete'])
  849. if self.require_all_fields:
  850. # Set 'required' to False on the individual fields, because the
  851. # required validation will be handled by MultiValueField, not
  852. # by those individual fields.
  853. f.required = False
  854. self.fields = fields
  855. def __deepcopy__(self, memo):
  856. result = super(MultiValueField, self).__deepcopy__(memo)
  857. result.fields = tuple([x.__deepcopy__(memo) for x in self.fields])
  858. return result
  859. def validate(self, value):
  860. pass
  861. def clean(self, value):
  862. """
  863. Validates every value in the given list. A value is validated against
  864. the corresponding Field in self.fields.
  865. For example, if this MultiValueField was instantiated with
  866. fields=(DateField(), TimeField()), clean() would call
  867. DateField.clean(value[0]) and TimeField.clean(value[1]).
  868. """
  869. clean_data = []
  870. errors = []
  871. if not value or isinstance(value, (list, tuple)):
  872. if not value or not [v for v in value if v not in self.empty_values]:
  873. if self.required:
  874. raise ValidationError(self.error_messages['required'], code='required')
  875. else:
  876. return self.compress([])
  877. else:
  878. raise ValidationError(self.error_messages['invalid'], code='invalid')
  879. for i, field in enumerate(self.fields):
  880. try:
  881. field_value = value[i]
  882. except IndexError:
  883. field_value = None
  884. if field_value in self.empty_values:
  885. if self.require_all_fields:
  886. # Raise a 'required' error if the MultiValueField is
  887. # required and any field is empty.
  888. if self.required:
  889. raise ValidationError(self.error_messages['required'], code='required')
  890. elif field.required:
  891. # Otherwise, add an 'incomplete' error to the list of
  892. # collected errors and skip field cleaning, if a required
  893. # field is empty.
  894. if field.error_messages['incomplete'] not in errors:
  895. errors.append(field.error_messages['incomplete'])
  896. continue
  897. try:
  898. clean_data.append(field.clean(field_value))
  899. except ValidationError as e:
  900. # Collect all validation errors in a single list, which we'll
  901. # raise at the end of clean(), rather than raising a single
  902. # exception for the first error we encounter. Skip duplicates.
  903. errors.extend(m for m in e.error_list if m not in errors)
  904. if errors:
  905. raise ValidationError(errors)
  906. out = self.compress(clean_data)
  907. self.validate(out)
  908. self.run_validators(out)
  909. return out
  910. def compress(self, data_list):
  911. """
  912. Returns a single value for the given list of values. The values can be
  913. assumed to be valid.
  914. For example, if this MultiValueField was instantiated with
  915. fields=(DateField(), TimeField()), this might return a datetime
  916. object created by combining the date and time in data_list.
  917. """
  918. raise NotImplementedError('Subclasses must implement this method.')
  919. def _has_changed(self, initial, data):
  920. if initial is None:
  921. initial = ['' for x in range(0, len(data))]
  922. else:
  923. if not isinstance(initial, list):
  924. initial = self.widget.decompress(initial)
  925. for field, initial, data in zip(self.fields, initial, data):
  926. if field._has_changed(field.to_python(initial), data):
  927. return True
  928. return False
  929. class FilePathField(ChoiceField):
  930. def __init__(self, path, match=None, recursive=False, allow_files=True,
  931. allow_folders=False, required=True, widget=None, label=None,
  932. initial=None, help_text='', *args, **kwargs):
  933. self.path, self.match, self.recursive = path, match, recursive
  934. self.allow_files, self.allow_folders = allow_files, allow_folders
  935. super(FilePathField, self).__init__(choices=(), required=required,
  936. widget=widget, label=label, initial=initial, help_text=help_text,
  937. *args, **kwargs)
  938. if self.required:
  939. self.choices = []
  940. else:
  941. self.choices = [("", "---------")]
  942. if self.match is not None:
  943. self.match_re = re.compile(self.match)
  944. if recursive:
  945. for root, dirs, files in sorted(os.walk(self.path)):
  946. if self.allow_files:
  947. for f in files:
  948. if self.match is None or self.match_re.search(f):
  949. f = os.path.join(root, f)
  950. self.choices.append((f, f.replace(path, "", 1)))
  951. if self.allow_folders:
  952. for f in dirs:
  953. if f == '__pycache__':
  954. continue
  955. if self.match is None or self.match_re.search(f):
  956. f = os.path.join(root, f)
  957. self.choices.append((f, f.replace(path, "", 1)))
  958. else:
  959. try:
  960. for f in sorted(os.listdir(self.path)):
  961. if f == '__pycache__':
  962. continue
  963. full_file = os.path.join(self.path, f)
  964. if (((self.allow_files and os.path.isfile(full_file)) or
  965. (self.allow_folders and os.path.isdir(full_file))) and
  966. (self.match is None or self.match_re.search(f))):
  967. self.choices.append((full_file, f))
  968. except OSError:
  969. pass
  970. self.widget.choices = self.choices
  971. class SplitDateTimeField(MultiValueField):
  972. widget = SplitDateTimeWidget
  973. hidden_widget = SplitHiddenDateTimeWidget
  974. default_error_messages = {
  975. 'invalid_date': _('Enter a valid date.'),
  976. 'invalid_time': _('Enter a valid time.'),
  977. }
  978. def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs):
  979. errors = self.default_error_messages.copy()
  980. if 'error_messages' in kwargs:
  981. errors.update(kwargs['error_messages'])
  982. localize = kwargs.get('localize', False)
  983. fields = (
  984. DateField(input_formats=input_date_formats,
  985. error_messages={'invalid': errors['invalid_date']},
  986. localize=localize),
  987. TimeField(input_formats=input_time_formats,
  988. error_messages={'invalid': errors['invalid_time']},
  989. localize=localize),
  990. )
  991. super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
  992. def compress(self, data_list):
  993. if data_list:
  994. # Raise a validation error if time or date is empty
  995. # (possible if SplitDateTimeField has required=False).
  996. if data_list[0] in self.empty_values:
  997. raise ValidationError(self.error_messages['invalid_date'], code='invalid_date')
  998. if data_list[1] in self.empty_values:
  999. raise ValidationError(self.error_messages['invalid_time'], code='invalid_time')
  1000. result = datetime.datetime.combine(*data_list)
  1001. return from_current_timezone(result)
  1002. return None
  1003. class IPAddressField(CharField):
  1004. default_validators = [validators.validate_ipv4_address]
  1005. def __init__(self, *args, **kwargs):
  1006. warnings.warn("IPAddressField has been deprecated. Use GenericIPAddressField instead.",
  1007. RemovedInDjango19Warning)
  1008. super(IPAddressField, self).__init__(*args, **kwargs)
  1009. def to_python(self, value):
  1010. if value in self.empty_values:
  1011. return ''
  1012. return value.strip()
  1013. class GenericIPAddressField(CharField):
  1014. def __init__(self, protocol='both', unpack_ipv4=False, *args, **kwargs):
  1015. self.unpack_ipv4 = unpack_ipv4
  1016. self.default_validators = validators.ip_address_validators(protocol, unpack_ipv4)[0]
  1017. super(GenericIPAddressField, self).__init__(*args, **kwargs)
  1018. def to_python(self, value):
  1019. if value in self.empty_values:
  1020. return ''
  1021. value = value.strip()
  1022. if value and ':' in value:
  1023. return clean_ipv6_address(value, self.unpack_ipv4)
  1024. return value
  1025. class SlugField(CharField):
  1026. default_validators = [validators.validate_slug]
  1027. def clean(self, value):
  1028. value = self.to_python(value).strip()
  1029. return super(SlugField, self).clean(value)