forms.py 19 KB

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