Code

Opened 5 years ago

Closed 4 years ago

#12363 closed (duplicate)

Add add() method to ErrorDict class

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

Description

When doing form validation, in some cases you want to add an error message to a field other than the one you are currently validating, or add an error message to a field while inside the form's global clean() method. Usually this is because in order to validate a given field you need access to the data of another field that is not yet cleaned.

(For example, I have a form with two fields, "page" and "url", only one being required).

Currently, doing this requires accessing the form._errors dict and injecting the error message. This gets cumbersome when you want to "do the right thing" and not override existing error messages. I.e. you have to do something like:

if does_not_validate():
    self._errors.setdefault('the_field', ErrorList())
    self._errors['the_field'] += ['Fix this value']

I feel like it would be a nice addition of ErrorDict had something like add() or set() methods:

if does_not_validate():
    self.errors.add('the_field', 'Fix this value')

If you want to override all existing errors, you could do:

if does_not_validate():
    self.errors.set('the_field', 'Fix this value')

Possibly an alternative approach would be to allow raising a ValidationError with a dict:

if does_not_validate:
    raise ValidationError({'the_field': 'Fix this value'})

Attachments (0)

Change History (2)

comment:1 Changed 4 years ago by russellm

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted
  • Version 1.1 deleted

Broadly accepting the idea that the interface to dealing with ErrorDict can be improved, but I'm not sold on the specific API that has been proposed.

comment:2 Changed 4 years ago by Alex

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

Dupe of #5335.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.