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