Opened 7 years ago

Closed 7 years ago

#22318 closed New feature (fixed)

Adding Form.has_error() to easily check if a given error has happened.

Reported by: loic84 Owned by: nobody
Component: Forms Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Since #17413, it's possible to know, not only if a field has errors, but also what these errors are.

I propose that we add an API to easily check if a given error has happened.

This would enable logic like this in the view:

if form.has_error('email', 'not_verified'):
    context['email_not_verified'] = True

When a given error happens, I often want to display HTML that describes how to resolve the issue, (usually with links to the relevant sections in the docs which in turn require url reversing); stuffing these in the error message is neither clean (HTML belongs to the templates), nor practical. Following a given error, one may also want to perform actions that typically belongs to the views, like using the message framework.

Change History (4)

comment:1 Changed 7 years ago by loic84

Has patch: set
Needs documentation: set
Patch needs improvement: set


In term of API, I'm hesitating about how to best deal with non-field errors, add_error() accepts a value of None for them, but here has_error(None, 'invalid') could be ambiguous ("Is there any error with the 'invalid' code?" vs "Are there non-field errors with the 'invalid' code?").

With the current implementation non-field errors should be targeted with field=NON_FIELD_ERRORS.

comment:2 Changed 7 years ago by Marc Tamlyn

Triage Stage: UnreviewedAccepted

comment:3 Changed 7 years ago by loic84

Needs documentation: unset
Patch needs improvement: unset

comment:4 Changed 7 years ago by Tim Graham <timograham@…>

Resolution: fixed
Status: newclosed

In 7ac8380799eedb374621317b62ccf026d86ea245:

Fixed #22318 -- Added Form.has_error() to easily check if a given error has happened.

Note: See TracTickets for help on using tickets.
Back to Top