fields.py 47 KB

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