简体   繁体   English

Python Django如何在admin中与模型内联

[英]Python Django How to hook inlines with model in admin

in models.py , I have Image and Post model defined: models.py ,我定义了Image和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

in admin.py , I've defined as inlines: 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",)}

In the admin page, when I upload an image in the Post admin page, the image is stored. 在管理页面中,当我在发布管理页面中上载图像时,该图像将被存储。 But it's not hooked up with the Post. 但这并没有与邮报挂钩。 How to hook the image with the post when I upload in admin? 当我在管理员中上传时,如何将图片与帖子挂钩? I mean let the inline image uploaded become post's post_image. 我的意思是让上传的嵌入式图像成为发布的post_image。

Thanks! 谢谢!

As far as I understand thee is 1-to-1 relation between Image and Post models. 据我了解,您是ImagePost模型之间的Image关系。 So you should use the OneToOneField instead of two ForteignKey s. 因此,您应该使用OneToOneField而不是两个ForteignKey

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

And the delete the post_image field from the Post model. 然后从Post模型中删除post_image字段。

To access the image instance from the Post just write: 要从Post访问图像实例,只需编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM