fields.py 44 KB

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