以下は作業コードです。汎用フィールドを使用して、複数の画像を持つことができるモデルを作成しています。そして、私は管理者側でインラインを使用しています。このシステムの移植性を高めるために、inlineAdmin クラス内でモデルの (複数のイメージを持つことができる) クラス名を取得する方法が必要です...
#model mediaalbums
class MediaAlbum(models.Model):
content_type = models.ForeignKey(ContentType, null=True, blank=True)
media_type = models.CharField(max_length=5, choices= MEDIA_TYPE_CHOICES )
name = models.CharField(unique = True, max_length=50)
class ModelImage(Media):
album = models.ForeignKey(MediaAlbum, null=True, blank=True, limit_choices_to = {'media_type': 'image'})
file = ImageField(upload_to=get_path)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
#model sections
class Work(models.Model):
images = generic.GenericRelation(ModelImage)
#admin
class ModelImageInline(generic.GenericStackedInline):
model = ModelImage
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
field = super(ModelImageInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'album':
# for now i am getting the model's (that can have any number of images ) class name from the model's admin class' request object
# but i do not want to get it from there
className = request.className
field.queryset = field.queryset.filter(content_type__name=className) #building__exact = request._obj_
return field
class WorkAdmin(TranslationAdmin):
inlines = [ModelImageInline ]
def get_form(self, request, obj=None, **kwargs):
# pass the class name to inline class
request.className = 'work'
return super(WorkAdmin, self).get_form(request, obj, **kwargs)