#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

Description

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 12 months ago by loic84

  • Has patch set
  • Needs documentation set
  • Needs tests unset
  • Patch needs improvement set

POC https://github.com/loic/django/compare/has_error.

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 12 months ago by mjtamlyn

  • Triage Stage changed from Unreviewed to Accepted

comment:3 Changed 12 months ago by loic84

  • Needs documentation unset
  • Patch needs improvement unset

comment:4 Changed 12 months ago by Tim Graham <timograham@…>

  • Resolution set to fixed
  • Status changed from new to closed

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