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.
 
 
 
 

485 lines
19 KiB

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