Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Form-level errors #595

Merged
merged 2 commits into from
May 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Unreleased
:pr:`608`
- Choices shortcut for :class:`~fields.core.SelectMultipleField`.
:issue:`603` :pr:`605`
- Forms can have form-level errors. :issue:`55` :pr:`595`


Version 2.3.1
Expand Down
9 changes: 9 additions & 0 deletions docs/forms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ The Form class
A dict containing a list of errors for each field. Empty if the form
hasn't been validated, or there were no errors.

If present, the key ``None`` contains the content of
:attr:`~wtforms.forms.Form.form_errors`.

.. attribute:: form_errors

A list of form-level errors. Those are errors that does not concern a
particuliar field, but the whole form consistency. Those errors are
often set when overriding :meth:`~wtforms.forms.Form.validate`.

.. attribute:: meta

This is an object which contains various configuration options and also
Expand Down
2 changes: 1 addition & 1 deletion src/wtforms/fields/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ def bind(self, form, name, prefix="", translations=None, **kwargs):

def __repr__(self):
return "<UnboundField({}, {!r}, {!r})>".format(
self.field_class.__name__, self.args, self.kwargs,
self.field_class.__name__, self.args, self.kwargs
)


Expand Down
7 changes: 6 additions & 1 deletion src/wtforms/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ def __init__(self, fields, prefix="", meta=_default_meta):
field = meta.bind_field(self, unbound_field, options)
self._fields[name] = field

self.form_errors = []

def __iter__(self):
"""Iterate form fields in creation order."""
return iter(self._fields.values())
Expand Down Expand Up @@ -140,7 +142,10 @@ def data(self):

@property
def errors(self):
return {name: f.errors for name, f in self._fields.items() if f.errors}
errors = {name: f.errors for name, f in self._fields.items() if f.errors}
if self.form_errors:
errors[None] = self.form_errors
return errors


class FormMeta(type):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1154,7 +1154,7 @@ def _build_value(self, key, form_input, expected_html, data=unset_value):
data = form_input
if expected_html.startswith("type="):
expected_html = '<input id="{}" name="{}" {} value="{}">'.format(
key, key, expected_html, form_input,
key, key, expected_html, form_input
)
return {
"key": key,
Expand Down
25 changes: 25 additions & 0 deletions tests/test_form.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,31 @@ def extra(form, field):
form = F2(test="nope", other="extra")
assert not form.validate(extra_validators={"other": [extra]})

def test_form_level_errors(self):
class F(Form):
a = IntegerField()
b = IntegerField()

def validate(self):
if not super().validate():
return False

if (self.a.data + self.b.data) % 2 != 0:
self.form_errors.append("a + b should be even")
return False

return True

f = F(a=1, b=1)
assert f.validate()
assert not f.form_errors
assert not f.errors

f = F(a=0, b=1)
assert not f.validate()
assert ["a + b should be even"] == f.form_errors
assert ["a + b should be even"] == f.errors[None]

def test_field_adding_disabled(self):
form = self.F()
with pytest.raises(TypeError):
Expand Down