forms.py 20 KB

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