I have a Django model which can have many generic relationships. This is achieved by manually creating a junction model:
class ContentProjectContentItem(models.Model):
content_project = models.ForeignKey('ContentProject')
# Generic relations via Content Type Framework
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType)
item = generic.GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_project', 'object_id', 'content_type')
app_label = "cms"
That is related to the parent model via a ManyToManyField:
class ContentProject(models.Model):
title = models.CharField(max_length=100)
date_created = models.DateTimeField(auto_now_add=True)
# Related content (Assets, Resources, Media, etc)
content_items = models.ManyToManyField(ContentProjectContentItem)
I'm still developing my skills using the Django admin, so I'm unsure of how to create an inline that will allow me to add multiple ContentProjectContentItems to a ContentProject. I have tried using generic.GenericStackedInline
, but to no avail:
class ContentItemInline(generic.GenericStackedInline):
name = "content_project"
model = ContentProjectContentItem
class ContentProjectAdmin(MPTTModelAdmin):
list_display = ('title' , 'date_created')
search_fields = ('title' , 'date_created')
inlines = [
ContentItemInline,
]
I am simply seeing the standard ManyToMany multi-select for content_items
(which is what I would expect). I am unsure of how to make ContentProjectAdmin
aware of the junction table's generic relationships. Any thoughts?
I ended up implementing a custom change_view template to manually add form elements, and overrides for the form save method to handle this use case.
Not the prettiest solution, but effective nonetheless.