Opened 2 years ago
Last modified 7 months ago
#34007 assigned Cleanup/optimization
Single-field conditional UniqueContraint validation errors are classified as non-field-errors
Reported by: | David Sanders | Owned by: | David Sanders |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 4.1 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | yes |
Easy pickings: | no | UI/UX: | no |
Description
Mailing list discussion with Simon Charette: https://groups.google.com/g/django-developers/c/7QGy6i9oe4g/m/iCJE7be0AgAJ
Validating models with UniqueConstraint usually groups errors by field name:
class Test(Model): test = CharField(max_length=255) class Meta: constraints = [ UniqueConstraint(fields=["test"], name="unique"), ] Test.objects.create(test="abc") test = Test(test="abc") test.validate_constraints() django.core.exceptions.ValidationError: {'test': ['Test with this Test already exists.']}
However if a condition is added to the UniqueConstraint the validation error is categorised as a non-field error:
class Test(Model): test = CharField(max_length=255) class Meta: constraints = [ UniqueConstraint(fields=["test"], name="unique", condition=~Q(test="")), ] Test.objects.create(test="abc") test = Test(test="abc") test.validate_constraints() django.core.exceptions.ValidationError: {'__all__': ['Constraint “unique” is violated.']}
My proposal is to make the validation error a field-error for any unique constraint that only has a single field defined.
This affects the way custom error messages are defined (eg forms error_messages dict vs constraint violation_error_message).
It's been agreed that the error message wording should remain the generic "Constraint is violated" format as determining the correct wording involving conditions is non-trivial.
Change History (6)
comment:1 by , 2 years ago
comment:2 by , 2 years ago
Has patch: | set |
---|
comment:3 by , 2 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|---|
Owner: | changed from | to
Status: | new → assigned |
Summary: | Single-field conditional UniqueContraint validation errors are clasified as non-field-errors → Single-field conditional UniqueContraint validation errors are classified as non-field-errors |
Triage Stage: | Unreviewed → Accepted |
Type: | Uncategorized → Cleanup/optimization |
comment:4 by , 2 years ago
Patch needs improvement: | set |
---|
PR: https://github.com/django/django/pull/16054