#33832: Support M2M validation using signals
-------------------------------------+-------------------------------------
Reporter: ldeluigi | Owner: nobody
Type: New | Status: new
feature |
Component: | Version: 4.0
Uncategorized | Keywords: validation m2m
Severity: Normal | signal manytomany
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
MyModel has one ManyToManyField that links to AnotherModel.
For validation purposes I need to check the model after m2m relationships
have been set with custom logic based on the db (I can't check it before
m2m fields are populated)
At the moment, I'm raising ValidationError inside a signal receiver:
{{{
@receiver(m2m_changed, sender=MyModel.relationship.through)
def validator_from_signal(sender, instance, action, reverse, model,
**kwargs):
if action == 'post_add':
if reverse and not check_reverse(instance):
msg = f'AnotherModel {instance.id} violates validation
checks.'
logging.error(msg)
raise ValidationError(msg)
elif not reverse and not check(instance):
msg = f'MyModel {instance.id} violates validation checks.'
logging.error(msg)
raise ValidationError(msg)
}}}
It works, thanks to the transaction behaviour which in case of exception
rollbacks everything, but if the user submits a wrong MyModel or
AnotherModel (because of ManyToMany illegal relationships), in particular
with the Admin Form, they get a 500 internal server error. Which isn't
very user friendly...
I know this is the expected behaviour, but I'd like the Admin form to
handle ValidationError(s) and/or IntegrityError(s) from signal as normal
ValidationError. I can't implement this check inside the clean() method:
1. because m2m fields are not populated on the database at that stage
2. because it would only work for the admin form
What do you think?
--
Ticket URL: <https://code.djangoproject.com/ticket/33832>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/01070181d8a53344-967d4cf9-fc62-4476-bebd-d624eddf6f3a-000000%40eu-central-1.amazonses.com.