PageRenderTime 70ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/django/forms/fields.py

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