Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fields.py 47KB

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