1

I've a simple m2m relation of User and Client model in my Django 1.7 application. The m2m field is declared inside the Client model.

I wish to validate the User value of m2m relation when I save or update a Client instance. My validation consists to check if the User has some properties, if true save Client and the 2m2 relation, if false, raise a ValidationError.

Where I should put this logic?? I need to create an intermediate m2m model??

Fabrizio A
  • 3,072
  • 5
  • 24
  • 35
  • Possible duplicate of [Django: how to validate m2m relationships?](https://stackoverflow.com/questions/46362251/django-how-to-validate-m2m-relationships) – Bernd Wechner Feb 25 '19 at 11:07

2 Answers2

0

You should be able to add this validation in the pre_add stage of the m2m_changed signal handler.

Tom
  • 22,301
  • 5
  • 63
  • 96
  • 4
    Worth mentioning that you cannot raise `ValidationError` in signal handler code as it won't be handled correctly (in the admin, for example) and you may end up with a 500 error that is a headache to trace. – Burhan Khalid Oct 07 '14 at 13:43
0

As this validation should be enforced at both save and update, its best to override the clean_fields method of the model.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • How can I check in my Client clean_fields(self, exclude) overrided method if the User have some valid properties?? User is already saved in the db.... In the clean_fields() I have a self (Client) instance... that it have self.clients ManyToManyRelatedManager (from m2m relation). – Fabrizio A Oct 07 '14 at 13:47
  • You'll have a reference to it through the m2m field. – Burhan Khalid Oct 07 '14 at 13:49
  • Sorry, I don't understand. I've override the Client model (where I have declare a m2m users field) clean_fields() ... Inside that method I have, at runtime: self.users that is a ManyToManyRelatedManager not a specific user instance that has been selected. What is wrong? – Fabrizio A Oct 07 '14 at 13:55
  • 1
    Ok the self.users.all() return me the list of users of the client, but it is the list of the previous users... not the users that I have selected in the Client admin form and I need to validate. – Fabrizio A Oct 07 '14 at 14:34
  • If you only need validation on the admin form, then add the validation code there. – Burhan Khalid Oct 07 '14 at 15:12
  • No, I need validation on the model. I will use it with django_restframework later. At the time, I'm using an intermediate model and I've override there the clean(self) method... I'm not sure if this is a good practice. – Fabrizio A Oct 07 '14 at 15:15
  • m2m fields are updated after cleaning. Therefore this does not work. – Benedikt S. Vogler Dec 21 '20 at 09:57