下面是一个工作代码。我正在使用通用字段创建可以具有多个图像的模型。我在管理员端使用内联。我需要一种在 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)