forms.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. """
  2. Form classes
  3. """
  4. from __future__ import unicode_literals
  5. from collections import OrderedDict
  6. import copy
  7. import datetime
  8. import warnings
  9. from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
  10. from django.forms.fields import Field, FileField
  11. from django.forms.utils import flatatt, ErrorDict, ErrorList
  12. from django.forms.widgets import Media, MediaDefiningClass, TextInput, Textarea
  13. from django.utils.deprecation import RemovedInDjango18Warning, RemovedInDjango19Warning
  14. from django.utils.encoding import smart_text, force_text, python_2_unicode_compatible
  15. from django.utils.html import conditional_escape, format_html
  16. from django.utils.safestring import mark_safe
  17. from django.utils.translation import ugettext as _
  18. from django.utils import six
  19. __all__ = ('BaseForm', 'Form')
  20. def pretty_name(name):
  21. """Converts 'first_name' to 'First name'"""
  22. if not name:
  23. return ''
  24. return name.replace('_', ' ').capitalize()
  25. def get_declared_fields(bases, attrs, with_base_fields=True):
  26. """
  27. Create a list of form field instances from the passed in 'attrs', plus any
  28. similar fields on the base classes (in 'bases'). This is used by both the
  29. Form and ModelForm metaclasses.
  30. If 'with_base_fields' is True, all fields from the bases are used.
  31. Otherwise, only fields in the 'declared_fields' attribute on the bases are
  32. used. The distinction is useful in ModelForm subclassing.
  33. Also integrates any additional media definitions.
  34. """
  35. warnings.warn(
  36. "get_declared_fields is deprecated and will be removed in Django 1.9.",
  37. RemovedInDjango19Warning,
  38. stacklevel=2,
  39. )
  40. fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(six.iteritems(attrs)) if isinstance(obj, Field)]
  41. fields.sort(key=lambda x: x[1].creation_counter)
  42. # If this class is subclassing another Form, add that Form's fields.
  43. # Note that we loop over the bases in *reverse*. This is necessary in
  44. # order to preserve the correct order of fields.
  45. if with_base_fields:
  46. for base in bases[::-1]:
  47. if hasattr(base, 'base_fields'):
  48. fields = list(six.iteritems(base.base_fields)) + fields
  49. else:
  50. for base in bases[::-1]:
  51. if hasattr(base, 'declared_fields'):
  52. fields = list(six.iteritems(base.declared_fields)) + fields
  53. return OrderedDict(fields)
  54. class DeclarativeFieldsMetaclass(MediaDefiningClass):
  55. """
  56. Metaclass that collects Fields declared on the base classes.
  57. """
  58. def __new__(mcs, name, bases, attrs):
  59. # Collect fields from current class.
  60. current_fields = []
  61. for key, value in list(attrs.items()):
  62. if isinstance(value, Field):
  63. current_fields.append((key, value))
  64. attrs.pop(key)
  65. current_fields.sort(key=lambda x: x[1].creation_counter)
  66. attrs['declared_fields'] = OrderedDict(current_fields)
  67. new_class = (super(DeclarativeFieldsMetaclass, mcs)
  68. .__new__(mcs, name, bases, attrs))
  69. # Walk through the MRO.
  70. declared_fields = OrderedDict()
  71. for base in reversed(new_class.__mro__):
  72. # Collect fields from base class.
  73. if hasattr(base, 'declared_fields'):
  74. declared_fields.update(base.declared_fields)
  75. # Field shadowing.
  76. for attr, value in base.__dict__.items():
  77. if value is None and attr in declared_fields:
  78. declared_fields.pop(attr)
  79. new_class.base_fields = declared_fields
  80. new_class.declared_fields = declared_fields
  81. return new_class
  82. @python_2_unicode_compatible
  83. class BaseForm(object):
  84. # This is the main implementation of all the Form logic. Note that this
  85. # class is different than Form. See the comments by the Form class for more
  86. # information. Any improvements to the form API should be made to *this*
  87. # class, not to the Form class.
  88. def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
  89. initial=None, error_class=ErrorList, label_suffix=None,
  90. empty_permitted=False):
  91. self.is_bound = data is not None or files is not None
  92. self.data = data or {}
  93. self.files = files or {}
  94. self.auto_id = auto_id
  95. self.prefix = prefix
  96. self.initial = initial or {}
  97. self.error_class = error_class
  98. # Translators: This is the default suffix added to form field labels
  99. self.label_suffix = label_suffix if label_suffix is not None else _(':')
  100. self.empty_permitted = empty_permitted
  101. self._errors = None # Stores the errors after clean() has been called.
  102. self._changed_data = None
  103. # The base_fields class attribute is the *class-wide* definition of
  104. # fields. Because a particular *instance* of the class might want to
  105. # alter self.fields, we create self.fields here by copying base_fields.
  106. # Instances should always modify self.fields; they should not modify
  107. # self.base_fields.
  108. self.fields = copy.deepcopy(self.base_fields)
  109. def __str__(self):
  110. return self.as_table()
  111. def __iter__(self):
  112. for name in self.fields:
  113. yield self[name]
  114. def __getitem__(self, name):
  115. "Returns a BoundField with the given name."
  116. try:
  117. field = self.fields[name]
  118. except KeyError:
  119. raise KeyError(
  120. "Key %r not found in '%s'" % (name, self.__class__.__name__))
  121. return BoundField(self, field, name)
  122. @property
  123. def errors(self):
  124. "Returns an ErrorDict for the data provided for the form"
  125. if self._errors is None:
  126. self.full_clean()
  127. return self._errors
  128. def is_valid(self):
  129. """
  130. Returns True if the form has no errors. Otherwise, False. If errors are
  131. being ignored, returns False.
  132. """
  133. return self.is_bound and not bool(self.errors)
  134. def add_prefix(self, field_name):
  135. """
  136. Returns the field name with a prefix appended, if this Form has a
  137. prefix set.
  138. Subclasses may wish to override.
  139. """
  140. return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name
  141. def add_initial_prefix(self, field_name):
  142. """
  143. Add a 'initial' prefix for checking dynamic initial values
  144. """
  145. return 'initial-%s' % self.add_prefix(field_name)
  146. def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
  147. "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
  148. top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
  149. output, hidden_fields = [], []
  150. for name, field in self.fields.items():
  151. html_class_attr = ''
  152. bf = self[name]
  153. # Escape and cache in local variable.
  154. bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
  155. if bf.is_hidden:
  156. if bf_errors:
  157. top_errors.extend(
  158. [_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': force_text(e)}
  159. for e in bf_errors])
  160. hidden_fields.append(six.text_type(bf))
  161. else:
  162. # Create a 'class="..."' attribute if the row should have any
  163. # CSS classes applied.
  164. css_classes = bf.css_classes()
  165. if css_classes:
  166. html_class_attr = ' class="%s"' % css_classes
  167. if errors_on_separate_row and bf_errors:
  168. output.append(error_row % force_text(bf_errors))
  169. if bf.label:
  170. label = conditional_escape(force_text(bf.label))
  171. label = bf.label_tag(label) or ''
  172. else:
  173. label = ''
  174. if field.help_text:
  175. help_text = help_text_html % force_text(field.help_text)
  176. else:
  177. help_text = ''
  178. output.append(normal_row % {
  179. 'errors': force_text(bf_errors),
  180. 'label': force_text(label),
  181. 'field': six.text_type(bf),
  182. 'help_text': help_text,
  183. 'html_class_attr': html_class_attr,
  184. 'field_name': bf.html_name,
  185. })
  186. if top_errors:
  187. output.insert(0, error_row % force_text(top_errors))
  188. if hidden_fields: # Insert any hidden fields in the last row.
  189. str_hidden = ''.join(hidden_fields)
  190. if output:
  191. last_row = output[-1]
  192. # Chop off the trailing row_ender (e.g. '</td></tr>') and
  193. # insert the hidden fields.
  194. if not last_row.endswith(row_ender):
  195. # This can happen in the as_p() case (and possibly others
  196. # that users write): if there are only top errors, we may
  197. # not be able to conscript the last row for our purposes,
  198. # so insert a new, empty row.
  199. last_row = (normal_row % {'errors': '', 'label': '',
  200. 'field': '', 'help_text': '',
  201. 'html_class_attr': html_class_attr})
  202. output.append(last_row)
  203. output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
  204. else:
  205. # If there aren't any rows in the output, just append the
  206. # hidden fields.
  207. output.append(str_hidden)
  208. return mark_safe('\n'.join(output))
  209. def as_table(self):
  210. "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
  211. return self._html_output(
  212. normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
  213. error_row='<tr><td colspan="2">%s</td></tr>',
  214. row_ender='</td></tr>',
  215. help_text_html='<br /><span class="helptext">%s</span>',
  216. errors_on_separate_row=False)
  217. def as_ul(self):
  218. "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
  219. return self._html_output(
  220. normal_row='<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
  221. error_row='<li>%s</li>',
  222. row_ender='</li>',
  223. help_text_html=' <span class="helptext">%s</span>',
  224. errors_on_separate_row=False)
  225. def as_p(self):
  226. "Returns this form rendered as HTML <p>s."
  227. return self._html_output(
  228. normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
  229. error_row='%s',
  230. row_ender='</p>',
  231. help_text_html=' <span class="helptext">%s</span>',
  232. errors_on_separate_row=True)
  233. def non_field_errors(self):
  234. """
  235. Returns an ErrorList of errors that aren't associated with a particular
  236. field -- i.e., from Form.clean(). Returns an empty ErrorList if there
  237. are none.
  238. """
  239. return self.errors.get(NON_FIELD_ERRORS, self.error_class())
  240. def _raw_value(self, fieldname):
  241. """
  242. Returns the raw_value for a particular field name. This is just a
  243. convenient wrapper around widget.value_from_datadict.
  244. """
  245. field = self.fields[fieldname]
  246. prefix = self.add_prefix(fieldname)
  247. return field.widget.value_from_datadict(self.data, self.files, prefix)
  248. def add_error(self, field, error):
  249. """
  250. Update the content of `self._errors`.
  251. The `field` argument is the name of the field to which the errors
  252. should be added. If its value is None the errors will be treated as
  253. NON_FIELD_ERRORS.
  254. The `error` argument can be a single error, a list of errors, or a
  255. dictionary that maps field names to lists of errors. What we define as
  256. an "error" can be either a simple string or an instance of
  257. ValidationError with its message attribute set and what we define as
  258. list or dictionary can be an actual `list` or `dict` or an instance
  259. of ValidationError with its `error_list` or `error_dict` attribute set.
  260. If `error` is a dictionary, the `field` argument *must* be None and
  261. errors will be added to the fields that correspond to the keys of the
  262. dictionary.
  263. """
  264. if not isinstance(error, ValidationError):
  265. # Normalize to ValidationError and let its constructor
  266. # do the hard work of making sense of the input.
  267. error = ValidationError(error)
  268. if hasattr(error, 'error_dict'):
  269. if field is not None:
  270. raise TypeError(
  271. "The argument `field` must be `None` when the `error` "
  272. "argument contains errors for multiple fields."
  273. )
  274. else:
  275. error = error.error_dict
  276. else:
  277. error = {field or NON_FIELD_ERRORS: error.error_list}
  278. for field, error_list in error.items():
  279. if field not in self.errors:
  280. if field != NON_FIELD_ERRORS and field not in self.fields:
  281. raise ValueError(
  282. "'%s' has no field named '%s'." % (self.__class__.__name__, field))
  283. self._errors[field] = self.error_class()
  284. self._errors[field].extend(error_list)
  285. if field in self.cleaned_data:
  286. del self.cleaned_data[field]
  287. def full_clean(self):
  288. """
  289. Cleans all of self.data and populates self._errors and
  290. self.cleaned_data.
  291. """
  292. self._errors = ErrorDict()
  293. if not self.is_bound: # Stop further processing.
  294. return
  295. self.cleaned_data = {}
  296. # If the form is permitted to be empty, and none of the form data has
  297. # changed from the initial data, short circuit any validation.
  298. if self.empty_permitted and not self.has_changed():
  299. return
  300. self._clean_fields()
  301. self._clean_form()
  302. self._post_clean()
  303. def _clean_fields(self):
  304. for name, field in self.fields.items():
  305. # value_from_datadict() gets the data from the data dictionaries.
  306. # Each widget type knows how to retrieve its own data, because some
  307. # widgets split data over several HTML fields.
  308. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  309. try:
  310. if isinstance(field, FileField):
  311. initial = self.initial.get(name, field.initial)
  312. value = field.clean(value, initial)
  313. else:
  314. value = field.clean(value)
  315. self.cleaned_data[name] = value
  316. if hasattr(self, 'clean_%s' % name):
  317. value = getattr(self, 'clean_%s' % name)()
  318. self.cleaned_data[name] = value
  319. except ValidationError as e:
  320. self.add_error(name, e)
  321. def _clean_form(self):
  322. try:
  323. cleaned_data = self.clean()
  324. except ValidationError as e:
  325. self.add_error(None, e)
  326. else:
  327. if cleaned_data is not None:
  328. self.cleaned_data = cleaned_data
  329. def _post_clean(self):
  330. """
  331. An internal hook for performing additional cleaning after form cleaning
  332. is complete. Used for model validation in model forms.
  333. """
  334. pass
  335. def clean(self):
  336. """
  337. Hook for doing any extra form-wide cleaning after Field.clean() been
  338. called on every field. Any ValidationError raised by this method will
  339. not be associated with a particular field; it will have a special-case
  340. association with the field named '__all__'.
  341. """
  342. return self.cleaned_data
  343. def has_changed(self):
  344. """
  345. Returns True if data differs from initial.
  346. """
  347. return bool(self.changed_data)
  348. @property
  349. def changed_data(self):
  350. if self._changed_data is None:
  351. self._changed_data = []
  352. # XXX: For now we're asking the individual widgets whether or not the
  353. # data has changed. It would probably be more efficient to hash the
  354. # initial data, store it in a hidden field, and compare a hash of the
  355. # submitted data, but we'd need a way to easily get the string value
  356. # for a given field. Right now, that logic is embedded in the render
  357. # method of each widget.
  358. for name, field in self.fields.items():
  359. prefixed_name = self.add_prefix(name)
  360. data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
  361. if not field.show_hidden_initial:
  362. initial_value = self.initial.get(name, field.initial)
  363. if callable(initial_value):
  364. initial_value = initial_value()
  365. else:
  366. initial_prefixed_name = self.add_initial_prefix(name)
  367. hidden_widget = field.hidden_widget()
  368. try:
  369. initial_value = field.to_python(hidden_widget.value_from_datadict(
  370. self.data, self.files, initial_prefixed_name))
  371. except ValidationError:
  372. # Always assume data has changed if validation fails.
  373. self._changed_data.append(name)
  374. continue
  375. if hasattr(field.widget, '_has_changed'):
  376. warnings.warn("The _has_changed method on widgets is deprecated,"
  377. " define it at field level instead.",
  378. RemovedInDjango18Warning, stacklevel=2)
  379. if field.widget._has_changed(initial_value, data_value):
  380. self._changed_data.append(name)
  381. elif field._has_changed(initial_value, data_value):
  382. self._changed_data.append(name)
  383. return self._changed_data
  384. @property
  385. def media(self):
  386. """
  387. Provide a description of all media required to render the widgets on this form
  388. """
  389. media = Media()
  390. for field in self.fields.values():
  391. media = media + field.widget.media
  392. return media
  393. def is_multipart(self):
  394. """
  395. Returns True if the form needs to be multipart-encoded, i.e. it has
  396. FileInput. Otherwise, False.
  397. """
  398. for field in self.fields.values():
  399. if field.widget.needs_multipart_form:
  400. return True
  401. return False
  402. def hidden_fields(self):
  403. """
  404. Returns a list of all the BoundField objects that are hidden fields.
  405. Useful for manual form layout in templates.
  406. """
  407. return [field for field in self if field.is_hidden]
  408. def visible_fields(self):
  409. """
  410. Returns a list of BoundField objects that aren't hidden fields.
  411. The opposite of the hidden_fields() method.
  412. """
  413. return [field for field in self if not field.is_hidden]
  414. class Form(six.with_metaclass(DeclarativeFieldsMetaclass, BaseForm)):
  415. "A collection of Fields, plus their associated data."
  416. # This is a separate class from BaseForm in order to abstract the way
  417. # self.fields is specified. This class (Form) is the one that does the
  418. # fancy metaclass stuff purely for the semantic sugar -- it allows one
  419. # to define a form using declarative syntax.
  420. # BaseForm itself has no way of designating self.fields.
  421. @python_2_unicode_compatible
  422. class BoundField(object):
  423. "A Field plus data"
  424. def __init__(self, form, field, name):
  425. self.form = form
  426. self.field = field
  427. self.name = name
  428. self.html_name = form.add_prefix(name)
  429. self.html_initial_name = form.add_initial_prefix(name)
  430. self.html_initial_id = form.add_initial_prefix(self.auto_id)
  431. if self.field.label is None:
  432. self.label = pretty_name(name)
  433. else:
  434. self.label = self.field.label
  435. self.help_text = field.help_text or ''
  436. def __str__(self):
  437. """Renders this field as an HTML widget."""
  438. if self.field.show_hidden_initial:
  439. return self.as_widget() + self.as_hidden(only_initial=True)
  440. return self.as_widget()
  441. def __iter__(self):
  442. """
  443. Yields rendered strings that comprise all widgets in this BoundField.
  444. This really is only useful for RadioSelect widgets, so that you can
  445. iterate over individual radio buttons in a template.
  446. """
  447. id_ = self.field.widget.attrs.get('id') or self.auto_id
  448. attrs = {'id': id_} if id_ else {}
  449. for subwidget in self.field.widget.subwidgets(self.html_name, self.value(), attrs):
  450. yield subwidget
  451. def __len__(self):
  452. return len(list(self.__iter__()))
  453. def __getitem__(self, idx):
  454. return list(self.__iter__())[idx]
  455. @property
  456. def errors(self):
  457. """
  458. Returns an ErrorList for this field. Returns an empty ErrorList
  459. if there are none.
  460. """
  461. return self.form.errors.get(self.name, self.form.error_class())
  462. def as_widget(self, widget=None, attrs=None, only_initial=False):
  463. """
  464. Renders the field by rendering the passed widget, adding any HTML
  465. attributes passed as attrs. If no widget is specified, then the
  466. field's default widget will be used.
  467. """
  468. if not widget:
  469. widget = self.field.widget
  470. if self.field.localize:
  471. widget.is_localized = True
  472. attrs = attrs or {}
  473. auto_id = self.auto_id
  474. if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
  475. if not only_initial:
  476. attrs['id'] = auto_id
  477. else:
  478. attrs['id'] = self.html_initial_id
  479. if not only_initial:
  480. name = self.html_name
  481. else:
  482. name = self.html_initial_name
  483. return force_text(widget.render(name, self.value(), attrs=attrs))
  484. def as_text(self, attrs=None, **kwargs):
  485. """
  486. Returns a string of HTML for representing this as an <input type="text">.
  487. """
  488. return self.as_widget(TextInput(), attrs, **kwargs)
  489. def as_textarea(self, attrs=None, **kwargs):
  490. "Returns a string of HTML for representing this as a <textarea>."
  491. return self.as_widget(Textarea(), attrs, **kwargs)
  492. def as_hidden(self, attrs=None, **kwargs):
  493. """
  494. Returns a string of HTML for representing this as an <input type="hidden">.
  495. """
  496. return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
  497. @property
  498. def data(self):
  499. """
  500. Returns the data for this BoundField, or None if it wasn't given.
  501. """
  502. return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
  503. def value(self):
  504. """
  505. Returns the value for this BoundField, using the initial value if
  506. the form is not bound or the data otherwise.
  507. """
  508. if not self.form.is_bound:
  509. data = self.form.initial.get(self.name, self.field.initial)
  510. if callable(data):
  511. data = data()
  512. # If this is an auto-generated default date, nix the
  513. # microseconds for standardized handling. See #22502.
  514. if (isinstance(data, (datetime.datetime, datetime.time)) and
  515. not getattr(self.field.widget, 'supports_microseconds', True)):
  516. data = data.replace(microsecond=0)
  517. else:
  518. data = self.field.bound_data(
  519. self.data, self.form.initial.get(self.name, self.field.initial)
  520. )
  521. return self.field.prepare_value(data)
  522. def label_tag(self, contents=None, attrs=None, label_suffix=None):
  523. """
  524. Wraps the given contents in a <label>, if the field has an ID attribute.
  525. contents should be 'mark_safe'd to avoid HTML escaping. If contents
  526. aren't given, uses the field's HTML-escaped label.
  527. If attrs are given, they're used as HTML attributes on the <label> tag.
  528. label_suffix allows overriding the form's label_suffix.
  529. """
  530. contents = contents or self.label
  531. # Only add the suffix if the label does not end in punctuation.
  532. label_suffix = label_suffix if label_suffix is not None else self.form.label_suffix
  533. # Translators: If found as last label character, these punctuation
  534. # characters will prevent the default label_suffix to be appended to the label
  535. if label_suffix and contents and contents[-1] not in _(':?.!'):
  536. contents = format_html('{0}{1}', contents, label_suffix)
  537. widget = self.field.widget
  538. id_ = widget.attrs.get('id') or self.auto_id
  539. if id_:
  540. id_for_label = widget.id_for_label(id_)
  541. if id_for_label:
  542. attrs = dict(attrs or {}, **{'for': id_for_label})
  543. attrs = flatatt(attrs) if attrs else ''
  544. contents = format_html('<label{0}>{1}</label>', attrs, contents)
  545. else:
  546. contents = conditional_escape(contents)
  547. return mark_safe(contents)
  548. def css_classes(self, extra_classes=None):
  549. """
  550. Returns a string of space-separated CSS classes for this field.
  551. """
  552. if hasattr(extra_classes, 'split'):
  553. extra_classes = extra_classes.split()
  554. extra_classes = set(extra_classes or [])
  555. if self.errors and hasattr(self.form, 'error_css_class'):
  556. extra_classes.add(self.form.error_css_class)
  557. if self.field.required and hasattr(self.form, 'required_css_class'):
  558. extra_classes.add(self.form.required_css_class)
  559. return ' '.join(extra_classes)
  560. @property
  561. def is_hidden(self):
  562. "Returns True if this BoundField's widget is hidden."
  563. return self.field.widget.is_hidden
  564. @property
  565. def auto_id(self):
  566. """
  567. Calculates and returns the ID attribute for this BoundField, if the
  568. associated Form has specified auto_id. Returns an empty string otherwise.
  569. """
  570. auto_id = self.form.auto_id
  571. if auto_id and '%s' in smart_text(auto_id):
  572. return smart_text(auto_id) % self.html_name
  573. elif auto_id:
  574. return self.html_name
  575. return ''
  576. @property
  577. def id_for_label(self):
  578. """
  579. Wrapper around the field widget's `id_for_label` method.
  580. Useful, for example, for focusing on this field regardless of whether
  581. it has a single widget or a MultiWidget.
  582. """
  583. widget = self.field.widget
  584. id_ = widget.attrs.get('id') or self.auto_id
  585. return widget.id_for_label(id_)