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

/Lib/site-packages/django/forms/fields.py

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