2
0

forms.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. """
  2. Form classes
  3. """
  4. import copy
  5. import datetime
  6. import warnings
  7. from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
  8. from django.forms.fields import Field, FileField
  9. from django.forms.utils import ErrorDict, ErrorList, RenderableFormMixin
  10. from django.forms.widgets import Media, MediaDefiningClass
  11. from django.utils.datastructures import MultiValueDict
  12. from django.utils.deprecation import RemovedInDjango50Warning
  13. from django.utils.functional import cached_property
  14. from django.utils.html import conditional_escape
  15. from django.utils.safestring import SafeString, mark_safe
  16. from django.utils.translation import gettext as _
  17. from .renderers import get_default_renderer
  18. __all__ = ('BaseForm', 'Form')
  19. class DeclarativeFieldsMetaclass(MediaDefiningClass):
  20. """Collect Fields declared on the base classes."""
  21. def __new__(mcs, name, bases, attrs):
  22. # Collect fields from current class and remove them from attrs.
  23. attrs['declared_fields'] = {
  24. key: attrs.pop(key) for key, value in list(attrs.items())
  25. if isinstance(value, Field)
  26. }
  27. new_class = super().__new__(mcs, name, bases, attrs)
  28. # Walk through the MRO.
  29. declared_fields = {}
  30. for base in reversed(new_class.__mro__):
  31. # Collect fields from base class.
  32. if hasattr(base, 'declared_fields'):
  33. declared_fields.update(base.declared_fields)
  34. # Field shadowing.
  35. for attr, value in base.__dict__.items():
  36. if value is None and attr in declared_fields:
  37. declared_fields.pop(attr)
  38. new_class.base_fields = declared_fields
  39. new_class.declared_fields = declared_fields
  40. return new_class
  41. class BaseForm(RenderableFormMixin):
  42. """
  43. The main implementation of all the Form logic. Note that this class is
  44. different than Form. See the comments by the Form class for more info. Any
  45. improvements to the form API should be made to this class, not to the Form
  46. class.
  47. """
  48. default_renderer = None
  49. field_order = None
  50. prefix = None
  51. use_required_attribute = True
  52. template_name = 'django/forms/default.html'
  53. template_name_p = 'django/forms/p.html'
  54. template_name_table = 'django/forms/table.html'
  55. template_name_ul = 'django/forms/ul.html'
  56. template_name_label = 'django/forms/label.html'
  57. def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
  58. initial=None, error_class=ErrorList, label_suffix=None,
  59. empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):
  60. self.is_bound = data is not None or files is not None
  61. self.data = MultiValueDict() if data is None else data
  62. self.files = MultiValueDict() if files is None else files
  63. self.auto_id = auto_id
  64. if prefix is not None:
  65. self.prefix = prefix
  66. self.initial = initial or {}
  67. self.error_class = error_class
  68. # Translators: This is the default suffix added to form field labels
  69. self.label_suffix = label_suffix if label_suffix is not None else _(':')
  70. self.empty_permitted = empty_permitted
  71. self._errors = None # Stores the errors after clean() has been called.
  72. # The base_fields class attribute is the *class-wide* definition of
  73. # fields. Because a particular *instance* of the class might want to
  74. # alter self.fields, we create self.fields here by copying base_fields.
  75. # Instances should always modify self.fields; they should not modify
  76. # self.base_fields.
  77. self.fields = copy.deepcopy(self.base_fields)
  78. self._bound_fields_cache = {}
  79. self.order_fields(self.field_order if field_order is None else field_order)
  80. if use_required_attribute is not None:
  81. self.use_required_attribute = use_required_attribute
  82. if self.empty_permitted and self.use_required_attribute:
  83. raise ValueError(
  84. 'The empty_permitted and use_required_attribute arguments may '
  85. 'not both be True.'
  86. )
  87. # Initialize form renderer. Use a global default if not specified
  88. # either as an argument or as self.default_renderer.
  89. if renderer is None:
  90. if self.default_renderer is None:
  91. renderer = get_default_renderer()
  92. else:
  93. renderer = self.default_renderer
  94. if isinstance(self.default_renderer, type):
  95. renderer = renderer()
  96. self.renderer = renderer
  97. def order_fields(self, field_order):
  98. """
  99. Rearrange the fields according to field_order.
  100. field_order is a list of field names specifying the order. Append fields
  101. not included in the list in the default order for backward compatibility
  102. with subclasses not overriding field_order. If field_order is None,
  103. keep all fields in the order defined in the class. Ignore unknown
  104. fields in field_order to allow disabling fields in form subclasses
  105. without redefining ordering.
  106. """
  107. if field_order is None:
  108. return
  109. fields = {}
  110. for key in field_order:
  111. try:
  112. fields[key] = self.fields.pop(key)
  113. except KeyError: # ignore unknown fields
  114. pass
  115. fields.update(self.fields) # add remaining fields in original order
  116. self.fields = fields
  117. def __repr__(self):
  118. if self._errors is None:
  119. is_valid = "Unknown"
  120. else:
  121. is_valid = self.is_bound and not self._errors
  122. return '<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>' % {
  123. 'cls': self.__class__.__name__,
  124. 'bound': self.is_bound,
  125. 'valid': is_valid,
  126. 'fields': ';'.join(self.fields),
  127. }
  128. def _bound_items(self):
  129. """Yield (name, bf) pairs, where bf is a BoundField object."""
  130. for name in self.fields:
  131. yield name, self[name]
  132. def __iter__(self):
  133. """Yield the form's fields as BoundField objects."""
  134. for name in self.fields:
  135. yield self[name]
  136. def __getitem__(self, name):
  137. """Return a BoundField with the given name."""
  138. try:
  139. return self._bound_fields_cache[name]
  140. except KeyError:
  141. pass
  142. try:
  143. field = self.fields[name]
  144. except KeyError:
  145. raise KeyError(
  146. "Key '%s' not found in '%s'. Choices are: %s." % (
  147. name,
  148. self.__class__.__name__,
  149. ', '.join(sorted(self.fields)),
  150. )
  151. )
  152. bound_field = field.get_bound_field(self, name)
  153. self._bound_fields_cache[name] = bound_field
  154. return bound_field
  155. @property
  156. def errors(self):
  157. """Return an ErrorDict for the data provided for the form."""
  158. if self._errors is None:
  159. self.full_clean()
  160. return self._errors
  161. def is_valid(self):
  162. """Return True if the form has no errors, or False otherwise."""
  163. return self.is_bound and not self.errors
  164. def add_prefix(self, field_name):
  165. """
  166. Return the field name with a prefix appended, if this Form has a
  167. prefix set.
  168. Subclasses may wish to override.
  169. """
  170. return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name
  171. def add_initial_prefix(self, field_name):
  172. """Add an 'initial' prefix for checking dynamic initial values."""
  173. return 'initial-%s' % self.add_prefix(field_name)
  174. def _widget_data_value(self, widget, html_name):
  175. # value_from_datadict() gets the data from the data dictionaries.
  176. # Each widget type knows how to retrieve its own data, because some
  177. # widgets split data over several HTML fields.
  178. return widget.value_from_datadict(self.data, self.files, html_name)
  179. def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
  180. "Output HTML. Used by as_table(), as_ul(), as_p()."
  181. warnings.warn(
  182. 'django.forms.BaseForm._html_output() is deprecated. '
  183. 'Please use .render() and .get_context() instead.',
  184. RemovedInDjango50Warning,
  185. stacklevel=2,
  186. )
  187. # Errors that should be displayed above all fields.
  188. top_errors = self.non_field_errors().copy()
  189. output, hidden_fields = [], []
  190. for name, bf in self._bound_items():
  191. field = bf.field
  192. html_class_attr = ''
  193. bf_errors = self.error_class(bf.errors)
  194. if bf.is_hidden:
  195. if bf_errors:
  196. top_errors.extend(
  197. [_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': str(e)}
  198. for e in bf_errors])
  199. hidden_fields.append(str(bf))
  200. else:
  201. # Create a 'class="..."' attribute if the row should have any
  202. # CSS classes applied.
  203. css_classes = bf.css_classes()
  204. if css_classes:
  205. html_class_attr = ' class="%s"' % css_classes
  206. if errors_on_separate_row and bf_errors:
  207. output.append(error_row % str(bf_errors))
  208. if bf.label:
  209. label = conditional_escape(bf.label)
  210. label = bf.label_tag(label) or ''
  211. else:
  212. label = ''
  213. if field.help_text:
  214. help_text = help_text_html % field.help_text
  215. else:
  216. help_text = ''
  217. output.append(normal_row % {
  218. 'errors': bf_errors,
  219. 'label': label,
  220. 'field': bf,
  221. 'help_text': help_text,
  222. 'html_class_attr': html_class_attr,
  223. 'css_classes': css_classes,
  224. 'field_name': bf.html_name,
  225. })
  226. if top_errors:
  227. output.insert(0, error_row % top_errors)
  228. if hidden_fields: # Insert any hidden fields in the last row.
  229. str_hidden = ''.join(hidden_fields)
  230. if output:
  231. last_row = output[-1]
  232. # Chop off the trailing row_ender (e.g. '</td></tr>') and
  233. # insert the hidden fields.
  234. if not last_row.endswith(row_ender):
  235. # This can happen in the as_p() case (and possibly others
  236. # that users write): if there are only top errors, we may
  237. # not be able to conscript the last row for our purposes,
  238. # so insert a new, empty row.
  239. last_row = (normal_row % {
  240. 'errors': '',
  241. 'label': '',
  242. 'field': '',
  243. 'help_text': '',
  244. 'html_class_attr': html_class_attr,
  245. 'css_classes': '',
  246. 'field_name': '',
  247. })
  248. output.append(last_row)
  249. output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
  250. else:
  251. # If there aren't any rows in the output, just append the
  252. # hidden fields.
  253. output.append(str_hidden)
  254. return mark_safe('\n'.join(output))
  255. def get_context(self):
  256. fields = []
  257. hidden_fields = []
  258. top_errors = self.non_field_errors().copy()
  259. for name, bf in self._bound_items():
  260. bf_errors = self.error_class(bf.errors, renderer=self.renderer)
  261. if bf.is_hidden:
  262. if bf_errors:
  263. top_errors += [
  264. _('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': str(e)}
  265. for e in bf_errors
  266. ]
  267. hidden_fields.append(bf)
  268. else:
  269. errors_str = str(bf_errors)
  270. # RemovedInDjango50Warning.
  271. if not isinstance(errors_str, SafeString):
  272. warnings.warn(
  273. f'Returning a plain string from '
  274. f'{self.error_class.__name__} is deprecated. Please '
  275. f'customize via the template system instead.',
  276. RemovedInDjango50Warning,
  277. )
  278. errors_str = mark_safe(errors_str)
  279. fields.append((bf, errors_str))
  280. return {
  281. 'form': self,
  282. 'fields': fields,
  283. 'hidden_fields': hidden_fields,
  284. 'errors': top_errors,
  285. }
  286. def non_field_errors(self):
  287. """
  288. Return an ErrorList of errors that aren't associated with a particular
  289. field -- i.e., from Form.clean(). Return an empty ErrorList if there
  290. are none.
  291. """
  292. return self.errors.get(
  293. NON_FIELD_ERRORS,
  294. self.error_class(error_class='nonfield', renderer=self.renderer),
  295. )
  296. def add_error(self, field, error):
  297. """
  298. Update the content of `self._errors`.
  299. The `field` argument is the name of the field to which the errors
  300. should be added. If it's None, treat the errors as NON_FIELD_ERRORS.
  301. The `error` argument can be a single error, a list of errors, or a
  302. dictionary that maps field names to lists of errors. An "error" can be
  303. either a simple string or an instance of ValidationError with its
  304. message attribute set and a "list or dictionary" can be an actual
  305. `list` or `dict` or an instance of ValidationError with its
  306. `error_list` or `error_dict` attribute set.
  307. If `error` is a dictionary, the `field` argument *must* be None and
  308. errors will be added to the fields that correspond to the keys of the
  309. dictionary.
  310. """
  311. if not isinstance(error, ValidationError):
  312. # Normalize to ValidationError and let its constructor
  313. # do the hard work of making sense of the input.
  314. error = ValidationError(error)
  315. if hasattr(error, 'error_dict'):
  316. if field is not None:
  317. raise TypeError(
  318. "The argument `field` must be `None` when the `error` "
  319. "argument contains errors for multiple fields."
  320. )
  321. else:
  322. error = error.error_dict
  323. else:
  324. error = {field or NON_FIELD_ERRORS: error.error_list}
  325. for field, error_list in error.items():
  326. if field not in self.errors:
  327. if field != NON_FIELD_ERRORS and field not in self.fields:
  328. raise ValueError(
  329. "'%s' has no field named '%s'." % (self.__class__.__name__, field))
  330. if field == NON_FIELD_ERRORS:
  331. self._errors[field] = self.error_class(error_class='nonfield', renderer=self.renderer)
  332. else:
  333. self._errors[field] = self.error_class(renderer=self.renderer)
  334. self._errors[field].extend(error_list)
  335. if field in self.cleaned_data:
  336. del self.cleaned_data[field]
  337. def has_error(self, field, code=None):
  338. return field in self.errors and (
  339. code is None or
  340. any(error.code == code for error in self.errors.as_data()[field])
  341. )
  342. def full_clean(self):
  343. """
  344. Clean all of self.data and populate self._errors and self.cleaned_data.
  345. """
  346. self._errors = ErrorDict()
  347. if not self.is_bound: # Stop further processing.
  348. return
  349. self.cleaned_data = {}
  350. # If the form is permitted to be empty, and none of the form data has
  351. # changed from the initial data, short circuit any validation.
  352. if self.empty_permitted and not self.has_changed():
  353. return
  354. self._clean_fields()
  355. self._clean_form()
  356. self._post_clean()
  357. def _clean_fields(self):
  358. for name, bf in self._bound_items():
  359. field = bf.field
  360. value = bf.initial if field.disabled else bf.data
  361. try:
  362. if isinstance(field, FileField):
  363. value = field.clean(value, bf.initial)
  364. else:
  365. value = field.clean(value)
  366. self.cleaned_data[name] = value
  367. if hasattr(self, 'clean_%s' % name):
  368. value = getattr(self, 'clean_%s' % name)()
  369. self.cleaned_data[name] = value
  370. except ValidationError as e:
  371. self.add_error(name, e)
  372. def _clean_form(self):
  373. try:
  374. cleaned_data = self.clean()
  375. except ValidationError as e:
  376. self.add_error(None, e)
  377. else:
  378. if cleaned_data is not None:
  379. self.cleaned_data = cleaned_data
  380. def _post_clean(self):
  381. """
  382. An internal hook for performing additional cleaning after form cleaning
  383. is complete. Used for model validation in model forms.
  384. """
  385. pass
  386. def clean(self):
  387. """
  388. Hook for doing any extra form-wide cleaning after Field.clean() has been
  389. called on every field. Any ValidationError raised by this method will
  390. not be associated with a particular field; it will have a special-case
  391. association with the field named '__all__'.
  392. """
  393. return self.cleaned_data
  394. def has_changed(self):
  395. """Return True if data differs from initial."""
  396. return bool(self.changed_data)
  397. @cached_property
  398. def changed_data(self):
  399. return [name for name, bf in self._bound_items() if bf._has_changed()]
  400. @property
  401. def media(self):
  402. """Return all media required to render the widgets on this form."""
  403. media = Media()
  404. for field in self.fields.values():
  405. media = media + field.widget.media
  406. return media
  407. def is_multipart(self):
  408. """
  409. Return True if the form needs to be multipart-encoded, i.e. it has
  410. FileInput, or False otherwise.
  411. """
  412. return any(field.widget.needs_multipart_form for field in self.fields.values())
  413. def hidden_fields(self):
  414. """
  415. Return a list of all the BoundField objects that are hidden fields.
  416. Useful for manual form layout in templates.
  417. """
  418. return [field for field in self if field.is_hidden]
  419. def visible_fields(self):
  420. """
  421. Return a list of BoundField objects that aren't hidden fields.
  422. The opposite of the hidden_fields() method.
  423. """
  424. return [field for field in self if not field.is_hidden]
  425. def get_initial_for_field(self, field, field_name):
  426. """
  427. Return initial data for field on form. Use initial data from the form
  428. or the field, in that order. Evaluate callable values.
  429. """
  430. value = self.initial.get(field_name, field.initial)
  431. if callable(value):
  432. value = value()
  433. # If this is an auto-generated default date, nix the microseconds
  434. # for standardized handling. See #22502.
  435. if (isinstance(value, (datetime.datetime, datetime.time)) and
  436. not field.widget.supports_microseconds):
  437. value = value.replace(microsecond=0)
  438. return value
  439. class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
  440. "A collection of Fields, plus their associated data."
  441. # This is a separate class from BaseForm in order to abstract the way
  442. # self.fields is specified. This class (Form) is the one that does the
  443. # fancy metaclass stuff purely for the semantic sugar -- it allows one
  444. # to define a form using declarative syntax.
  445. # BaseForm itself has no way of designating self.fields.