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 44KB

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