fields.py 48 KB

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