form.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import itertools
  2. from collections import OrderedDict
  3. from wtforms.meta import DefaultMeta
  4. from wtforms.utils import unset_value
  5. __all__ = ("BaseForm", "Form")
  6. _default_meta = DefaultMeta()
  7. class BaseForm:
  8. """
  9. Base Form Class. Provides core behaviour like field construction,
  10. validation, and data and error proxying.
  11. """
  12. def __init__(self, fields, prefix="", meta=_default_meta):
  13. """
  14. :param fields:
  15. A dict or sequence of 2-tuples of partially-constructed fields.
  16. :param prefix:
  17. If provided, all fields will have their name prefixed with the
  18. value.
  19. :param meta:
  20. A meta instance which is used for configuration and customization
  21. of WTForms behaviors.
  22. """
  23. if prefix and prefix[-1] not in "-_;:/.":
  24. prefix += "-"
  25. self.meta = meta
  26. self._prefix = prefix
  27. self._fields = OrderedDict()
  28. if hasattr(fields, "items"):
  29. fields = fields.items()
  30. translations = self.meta.get_translations(self)
  31. extra_fields = []
  32. if meta.csrf:
  33. self._csrf = meta.build_csrf(self)
  34. extra_fields.extend(self._csrf.setup_form(self))
  35. for name, unbound_field in itertools.chain(fields, extra_fields):
  36. field_name = unbound_field.name or name
  37. options = dict(name=field_name, prefix=prefix, translations=translations)
  38. field = meta.bind_field(self, unbound_field, options)
  39. self._fields[name] = field
  40. self.form_errors = []
  41. def __iter__(self):
  42. """Iterate form fields in creation order."""
  43. return iter(self._fields.values())
  44. def __contains__(self, name):
  45. """Returns `True` if the named field is a member of this form."""
  46. return name in self._fields
  47. def __getitem__(self, name):
  48. """Dict-style access to this form's fields."""
  49. return self._fields[name]
  50. def __setitem__(self, name, value):
  51. """Bind a field to this form."""
  52. self._fields[name] = value.bind(form=self, name=name, prefix=self._prefix)
  53. def __delitem__(self, name):
  54. """Remove a field from this form."""
  55. del self._fields[name]
  56. def populate_obj(self, obj):
  57. """
  58. Populates the attributes of the passed `obj` with data from the form's
  59. fields.
  60. :note: This is a destructive operation; Any attribute with the same name
  61. as a field will be overridden. Use with caution.
  62. """
  63. for name, field in self._fields.items():
  64. field.populate_obj(obj, name)
  65. def process(self, formdata=None, obj=None, data=None, extra_filters=None, **kwargs):
  66. """Process default and input data with each field.
  67. :param formdata: Input data coming from the client, usually
  68. ``request.form`` or equivalent. Should provide a "multi
  69. dict" interface to get a list of values for a given key,
  70. such as what Werkzeug, Django, and WebOb provide.
  71. :param obj: Take existing data from attributes on this object
  72. matching form field attributes. Only used if ``formdata`` is
  73. not passed.
  74. :param data: Take existing data from keys in this dict matching
  75. form field attributes. ``obj`` takes precedence if it also
  76. has a matching attribute. Only used if ``formdata`` is not
  77. passed.
  78. :param extra_filters: A dict mapping field attribute names to
  79. lists of extra filter functions to run. Extra filters run
  80. after filters passed when creating the field. If the form
  81. has ``filter_<fieldname>``, it is the last extra filter.
  82. :param kwargs: Merged with ``data`` to allow passing existing
  83. data as parameters. Overwrites any duplicate keys in
  84. ``data``. Only used if ``formdata`` is not passed.
  85. """
  86. formdata = self.meta.wrap_formdata(self, formdata)
  87. if data is not None:
  88. kwargs = dict(data, **kwargs)
  89. filters = extra_filters.copy() if extra_filters is not None else {}
  90. for name, field in self._fields.items():
  91. field_extra_filters = filters.get(name, [])
  92. inline_filter = getattr(self, "filter_%s" % name, None)
  93. if inline_filter is not None:
  94. field_extra_filters.append(inline_filter)
  95. if obj is not None and hasattr(obj, name):
  96. data = getattr(obj, name)
  97. elif name in kwargs:
  98. data = kwargs[name]
  99. else:
  100. data = unset_value
  101. field.process(formdata, data, extra_filters=field_extra_filters)
  102. def validate(self, extra_validators=None):
  103. """
  104. Validates the form by calling `validate` on each field.
  105. :param extra_validators:
  106. If provided, is a dict mapping field names to a sequence of
  107. callables which will be passed as extra validators to the field's
  108. `validate` method.
  109. Returns `True` if no errors occur.
  110. """
  111. success = True
  112. for name, field in self._fields.items():
  113. if extra_validators is not None and name in extra_validators:
  114. extra = extra_validators[name]
  115. else:
  116. extra = tuple()
  117. if not field.validate(self, extra):
  118. success = False
  119. return success
  120. @property
  121. def data(self):
  122. return {name: f.data for name, f in self._fields.items()}
  123. @property
  124. def errors(self):
  125. errors = {name: f.errors for name, f in self._fields.items() if f.errors}
  126. if self.form_errors:
  127. errors[None] = self.form_errors
  128. return errors
  129. class FormMeta(type):
  130. """
  131. The metaclass for `Form` and any subclasses of `Form`.
  132. `FormMeta`'s responsibility is to create the `_unbound_fields` list, which
  133. is a list of `UnboundField` instances sorted by their order of
  134. instantiation. The list is created at the first instantiation of the form.
  135. If any fields are added/removed from the form, the list is cleared to be
  136. re-generated on the next instantiation.
  137. Any properties which begin with an underscore or are not `UnboundField`
  138. instances are ignored by the metaclass.
  139. """
  140. def __init__(cls, name, bases, attrs):
  141. type.__init__(cls, name, bases, attrs)
  142. cls._unbound_fields = None
  143. cls._wtforms_meta = None
  144. def __call__(cls, *args, **kwargs):
  145. """
  146. Construct a new `Form` instance.
  147. Creates the `_unbound_fields` list and the internal `_wtforms_meta`
  148. subclass of the class Meta in order to allow a proper inheritance
  149. hierarchy.
  150. """
  151. if cls._unbound_fields is None:
  152. fields = []
  153. for name in dir(cls):
  154. if not name.startswith("_"):
  155. unbound_field = getattr(cls, name)
  156. if hasattr(unbound_field, "_formfield"):
  157. fields.append((name, unbound_field))
  158. # We keep the name as the second element of the sort
  159. # to ensure a stable sort.
  160. fields.sort(key=lambda x: (x[1].creation_counter, x[0]))
  161. cls._unbound_fields = fields
  162. # Create a subclass of the 'class Meta' using all the ancestors.
  163. if cls._wtforms_meta is None:
  164. bases = []
  165. for mro_class in cls.__mro__:
  166. if "Meta" in mro_class.__dict__:
  167. bases.append(mro_class.Meta)
  168. cls._wtforms_meta = type("Meta", tuple(bases), {})
  169. return type.__call__(cls, *args, **kwargs)
  170. def __setattr__(cls, name, value):
  171. """
  172. Add an attribute to the class, clearing `_unbound_fields` if needed.
  173. """
  174. if name == "Meta":
  175. cls._wtforms_meta = None
  176. elif not name.startswith("_") and hasattr(value, "_formfield"):
  177. cls._unbound_fields = None
  178. type.__setattr__(cls, name, value)
  179. def __delattr__(cls, name):
  180. """
  181. Remove an attribute from the class, clearing `_unbound_fields` if
  182. needed.
  183. """
  184. if not name.startswith("_"):
  185. cls._unbound_fields = None
  186. type.__delattr__(cls, name)
  187. class Form(BaseForm, metaclass=FormMeta):
  188. """
  189. Declarative Form base class. Extends BaseForm's core behaviour allowing
  190. fields to be defined on Form subclasses as class attributes.
  191. In addition, form and instance input data are taken at construction time
  192. and passed to `process()`.
  193. """
  194. Meta = DefaultMeta
  195. def __init__(
  196. self,
  197. formdata=None,
  198. obj=None,
  199. prefix="",
  200. data=None,
  201. meta=None,
  202. **kwargs,
  203. ):
  204. """
  205. :param formdata: Input data coming from the client, usually
  206. ``request.form`` or equivalent. Should provide a "multi
  207. dict" interface to get a list of values for a given key,
  208. such as what Werkzeug, Django, and WebOb provide.
  209. :param obj: Take existing data from attributes on this object
  210. matching form field attributes. Only used if ``formdata`` is
  211. not passed.
  212. :param prefix: If provided, all fields will have their name
  213. prefixed with the value. This is for distinguishing multiple
  214. forms on a single page. This only affects the HTML name for
  215. matching input data, not the Python name for matching
  216. existing data.
  217. :param data: Take existing data from keys in this dict matching
  218. form field attributes. ``obj`` takes precedence if it also
  219. has a matching attribute. Only used if ``formdata`` is not
  220. passed.
  221. :param meta: A dict of attributes to override on this form's
  222. :attr:`meta` instance.
  223. :param extra_filters: A dict mapping field attribute names to
  224. lists of extra filter functions to run. Extra filters run
  225. after filters passed when creating the field. If the form
  226. has ``filter_<fieldname>``, it is the last extra filter.
  227. :param kwargs: Merged with ``data`` to allow passing existing
  228. data as parameters. Overwrites any duplicate keys in
  229. ``data``. Only used if ``formdata`` is not passed.
  230. """
  231. meta_obj = self._wtforms_meta()
  232. if meta is not None and isinstance(meta, dict):
  233. meta_obj.update_values(meta)
  234. super().__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)
  235. for name, field in self._fields.items():
  236. # Set all the fields to attributes so that they obscure the class
  237. # attributes with the same names.
  238. setattr(self, name, field)
  239. self.process(formdata, obj, data=data, **kwargs)
  240. def __setitem__(self, name, value):
  241. raise TypeError("Fields may not be added to Form instances, only classes.")
  242. def __delitem__(self, name):
  243. del self._fields[name]
  244. setattr(self, name, None)
  245. def __delattr__(self, name):
  246. if name in self._fields:
  247. self.__delitem__(name)
  248. else:
  249. # This is done for idempotency, if we have a name which is a field,
  250. # we want to mask it by setting the value to None.
  251. unbound_field = getattr(self.__class__, name, None)
  252. if unbound_field is not None and hasattr(unbound_field, "_formfield"):
  253. setattr(self, name, None)
  254. else:
  255. super().__delattr__(name)
  256. def validate(self, extra_validators=None):
  257. """Validate the form by calling ``validate`` on each field.
  258. Returns ``True`` if validation passes.
  259. If the form defines a ``validate_<fieldname>`` method, it is
  260. appended as an extra validator for the field's ``validate``.
  261. :param extra_validators: A dict mapping field names to lists of
  262. extra validator methods to run. Extra validators run after
  263. validators passed when creating the field. If the form has
  264. ``validate_<fieldname>``, it is the last extra validator.
  265. """
  266. if extra_validators is not None:
  267. extra = extra_validators.copy()
  268. else:
  269. extra = {}
  270. for name in self._fields:
  271. inline = getattr(self.__class__, f"validate_{name}", None)
  272. if inline is not None:
  273. extra.setdefault(name, []).append(inline)
  274. return super().validate(extra)