Python Django如何在管理员中使用模型挂钩内联

时间:2015-03-25 00:02:41

标签: python django

models.py中,我定义了Image and Post模型:

class Image(models.Model):
    # name is the slug of the post
    name = models.CharField(max_length = 255)
    width = models.IntegerField(default = 0)
    height = models.IntegerField(default = 0)
    created = models.DateTimeField(auto_now_add = True)
    image = models.ImageField(upload_to = 'images/%Y/%m/%d')
    image_post = models.ForeignKey('Post')

    def get_image(self):
        return self.image.url

class Post(models.Model):
    title = models.CharField(max_length = 255)
    slug = models.SlugField(unique = True, max_length = 255)
    description = models.CharField(max_length = 255)
    content = models.TextField()
    published = models.BooleanField(default = True)
    created = models.DateTimeField(auto_now_add = True)
    post_image = models.ForeignKey(Image, null = True)

    def image_tag(self):
        return u'<img src="%s" />' % self.post_image.url

    image_tag.short_description = 'Image'
    image_tag.allow_tags = True

admin.py中,我将其定义为内联:

class ImageInline(admin.TabularInline):
    model = Image
    extra = 3

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'description')
    readonly_fields = ('image_tag',)
    exclude = ('post_image', )
    inlines = [ImageInline, ]
    list_filter = ('published', 'created')
    search_fields = ('title', 'description', 'content')
    date_hierarchy = 'created'
    save_on_top = True
    prepopulated_fieldes = {"slug" : ("title",)}

在管理页面中,当我在Post管理页面上传图像时,会存储图像。但它没有与邮政联系起来。我在管理员上传时如何将图片与帖子挂钩?我的意思是让上传的内嵌图像成为post的post_image。

谢谢!

1 个答案:

答案 0 :(得分:0)

据我所知,ImagePost模型之间存在一对一的关系。因此,您应该使用OneToOneField而不是两个ForteignKey

class Image(models.Model):
    ...
    post = models.OneToOneField('Post')

并从post_image模型中删除Post字段。

要从Post访问图像实例,只需写入:

def image_tag(self):
    return u'<img src="%s" />' % self.image.get_image()