I would like to be able to add inline Image objects to Gallery in Admin (as I try it in admin.py below). Problem is that Image model doesn't have content_type field. It raises exception. I would like to do the same with Videos objects. Here are my models.py and admin.py and more description below
My models.py
# -*- coding: utf-8 -*-
# Create your models here.
from apps.util import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.utils.translation import ugettext_lazy as _
class Image(models.Model):
"""
"""
title = models.CharField(_('Title'), max_length=255)
image = models.ImageField(upload_to="images")
pub_date = models.DateTimeField(_('Date published'))
def __unicode__(self):
return self.title
class Video(models.Model):
title = models.CharField(_('Title'), max_length=255)
video = models.FileField(upload_to="videos")
pub_date = models.DateTimeField(_('Date published'))
def __unicode__(self):
return self.title
class Gallery(models.Model):
title = models.CharField(_('Title'), max_length=255)
pub_date = models.DateTimeField(_('Date published'))
def __unicode__(self):
return self.title
class GalleryItem(models.Model):
gallery = models.ForeignKey(Gallery)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return str(self.object_id)
My admin.py
from django.contrib import admin
from apps.webmachinist.media.models import *
from apps.webmachinist.portfolio.models import *
from django.contrib.contenttypes import generic
class GalleryInline(generic.GenericTabularInline):
model = Image
class GalleryAdmin(admin.ModelAdmin):
inlines = [
GalleryInline,
]
admin.site.register(Image)
admin.site.register(Video)
admin.site.register(Gallery, GalleryAdmin)
admin.site.register(GalleryItem)
admin.site.register(PortfolioEntry)
I can do it easily in reverse way: to add Gallery to an Image, like that:
class GalleryInline(generic.GenericTabularInline):
model = GalleryItem
class GalleryAdmin(admin.ModelAdmin):
inlines = [
GalleryInline,
]
admin.site.register(Image, GalleryAdmin)
Then I can choose by Gallery title, though inline is for GalleryItems But it's not what I want. I just want to add Images to Galleries (and later Videos) not Galleries to Images.
Can it be done easily?
You shouldn't be inlining
Image
, but ratherGalleryItem
. Then from eachGalleryItem
you can associate it with whatever through it's generic foreign key.