Suppose I have a model with a ManyToManyField similar to this one (the
model Word has a language, too):
class Sentence(models.Model):
words = models.ManyToManyField(Word)
language = models.ForeignKey(Language)
def clean(self):
for word in self.words.all():
if word.language_id != self.language_id:
raise ValidationError('One of the words has a false
language')
When trying to add a new sentence (e.g. through django admin) I get
'Sentence' needs to have a value for field "sentence" before this
many-to-many relationship can be used.
There appears to be two ways to fix this: Put the validation logic in a
forms.ModelForm and then add that form to the admin.ModelAdmin. This fixes
the issue with the admin input but now my API is fragile. (Direct API
access can still add invalid data) The second option is to use m2m signals
which to me adds alot of complexity on top of what is normally a pretty
easy procedure.
Is it possible to develop Django to make something resembling the code
above work for validating related fields of a Many to Many? I understand
that the logic behind the ManyToMany is pretty complex and this would
likely require restructuring to accommodate. I'd like to help out if I
possible. The validation logic I've done so far has just been so darn
easy. Between Python's syntax and Django's ORM it's been a magical
experience. (I'm probably a bit spoiled)
I borrowed this example from the following source:
http://stackoverflow.com/questions/7986510/django-manytomany-model-validation
and made a minimal example case in Django 1.8:
https://github.com/blah73/mmtest
I also opened a ticket here:
https://code.djangoproject.com/ticket/24731
m2m signals intercept method:
http://schinckel.net/2012/02/06/pre-validating-many-to-many-fields./
--
You received this message because you are subscribed to the Google Groups
"Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-developers/a4f6da18-334f-4ab5-90e6-77e94a97510e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.