Anonymous committed d57e25e

Fiexed #3055 -- Validate that models target of a GenericRelation have a GenericForeignKey field.

Thanks jason for diagnosing the problem and Marcos Moyano for the patch.

Comments (0)

Files changed (3)


 import sys
+from django.contrib.contenttypes.generic import GenericForeignKey, GenericRelation
 from import color_style
 from django.utils.itercompat import is_iterable
+    any
+except NameError:
+    from django.utils.itercompat import any
 class ModelErrorCollection:
     def __init__(self, outfile=sys.stdout):
         self.errors = []
                 e.add(opts, "'%s' specifies an m2m relation through model %s, "
                     "which has not been installed" % (, f.rel.through)
+            elif isinstance(f, GenericRelation):
+                if not any([isinstance(vfield, GenericForeignKey) for vfield in]):
+                    e.add(opts, "Model '%s' must have a GenericForeignKey in "
+                        "order to create a GenericRelation that points to it."
+                        %
+                    )
             rel_opts =
             rel_name = RelatedObject(, cls, f).get_accessor_name()


         if not item:
             return False
     return True
+def any(iterable):
+    for item in iterable:
+        if item:
+            return True
+    return False


 This example exists purely to point out errors in models.
+from django.contrib.contenttypes import generic
 from django.db import models
 class FieldErrors(models.Model):
 class InvalidSetDefault(models.Model):
     fk = models.ForeignKey('self', on_delete=models.SET_DEFAULT)
+class Tag(models.Model):
+   name = models.CharField("name", max_length=20)
+class TaggedObject(models.Model):
+   object_id = models.PositiveIntegerField("Object ID")
+   tag = models.ForeignKey(Tag)
+   content_object = generic.GenericForeignKey()
+class UserTaggedObject(models.Model):
+   object_tag = models.ForeignKey(TaggedObject)
+class ArticleAttachment(models.Model):
+   tags = generic.GenericRelation(TaggedObject)
+   user_tags = generic.GenericRelation(UserTaggedObject)
 model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "max_length" attribute that is a positive integer.
 invalid_models.fielderrors: "charfield2": CharFields require a "max_length" attribute that is a positive integer.
 invalid_models.nonexistingorderingwithsingleunderscore: "ordering" refers to "does_not_exist", a field that doesn't exist.
 invalid_models.invalidsetnull: 'fk' specifies on_delete=SET_NULL, but cannot be null.
 invalid_models.invalidsetdefault: 'fk' specifies on_delete=SET_DEFAULT, but has no default value.
+invalid_models.articleattachment: Model 'UserTaggedObject' must have a GenericForeignKey in order to create a GenericRelation that points to it.