我希望能够将内联图像对象添加到管理中的图库(我在下面的admin.py中尝试)。问题是Image模型没有content_type字段。它引发了例外。我想对视频对象做同样的事情。这是我的models.py和admin.py以及下面的更多说明
我的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)
我的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)
我可以以相反的方式轻松完成:将图库添加到图像中,如下所示:
class GalleryInline(generic.GenericTabularInline):
model = GalleryItem
class GalleryAdmin(admin.ModelAdmin):
inlines = [
GalleryInline,
]
admin.site.register(Image, GalleryAdmin)
然后我可以选择Gallery标题,但内联是GalleryItems 但这不是我想要的。我只想将图像添加到图库(以及后来的视频),而不是将图库添加到图像。
可以轻松完成吗?
答案 0 :(得分:1)
您不应该内联Image
,而是GalleryItem
。然后,从每个GalleryItem
,您可以通过它的通用外键将其与任何内容相关联。