管理パネルで逆の一般的な関係を持つインラインオブジェクトを編集する方法は?

StackOverflow https://stackoverflow.com/questions/8839287

質問

adminのギャラリーにインライン画像オブジェクトを追加できるようにしたいと思います(以下のadmin.pyで試してみてください)。問題は、画像モデルには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)

それから私はギャラリーのタイトルで選択できますが、インラインはギャラリテム用ですが、それは私が望むものではありません。ギャラリーではなく、ギャラリー(および後のビデオ)に画像を画像に追加したいだけです。

簡単に行うことはできますか?

役に立ちましたか?

解決

インランスをとってはいけません Image, 、 むしろ GalleryItem. 。それぞれから GalleryItem 一般的な外部キーを通じて、それを何でも関連付けることができます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top