Opened 8 days ago

Closed 8 days ago

Last modified 8 days ago

#35910 closed New feature (duplicate)

Use violation_error_message on UniqueContraint when only fields and no constraint is provided

Reported by: James Walters Owned by:
Component: Database layer (models, ORM) Version:
Severity: Normal Keywords: forms, models, unique constraints
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have a model with the following UniqueConstraint:

models.UniqueConstraint(
  fields=["client", "location", "description", "affects_all_locations"],
  name="unique_desc_per_location_per_client",
  violation_error_message="A closure with this description already exists for this location (or all locations).",
)

Instead of seeing the error message I provided, I get "Closure with this Client, Location, Description and Affects all locations already exists." Upon consulting the documentation, I see that this is actually the intended behavior:

This message is not used for UniqueConstraints with fields and without a condition. Such UniqueConstraints show the same message as constraints defined
with Field.unique or in Meta.unique_together.

The default error message, however, gives the names of model fields that users know nothing about, and the message I'm trying to provide gives the user a better explanation about what's going on. Currently, I would have to override the form's own validation to show this error message. However, I don't think this should be necessary, given that I can provide a violation_error_message straight to the UniqueConstraint.

I'm filing this under models/ORM since this is specifically related to model validation, though reclassify it as Forms if that turns out to be more appropriate.

If we decide we want to go in this direction, I'm open to working on a patch, but I'll wait to see if we agree that this behavior should be changed.

Change History (2)

comment:1 by Simon Charette, 8 days ago

Resolution: duplicate
Status: newclosed

I think you ran into #35103 which was recently fixed by e970bb7ca71c00594b42a024a15a8ac007cc2c7a and will be part of Django 5.2.

You can try it out against main and refer to the updated documentation in the mean time.

In older versions, the provided UniqueConstraint.violation_error_code was not used when UniqueConstraint.fields was set without a UniqueConstraint.condition.

Please re-open if you believe you are running into a different issue.

comment:2 by James Walters, 8 days ago

Ah! This would be it. Sorry, looked to see if someone had already ran into this but didn't come across that ticket. Happy to see it fixed!

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