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.

forms.py 20KB

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