0
在models.py
,我有圖片和Post模型定義:的Python的Django如何掛鉤與模型內聯在管理
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_image。
謝謝!
它的工作原理,謝謝! – randomp 2015-03-25 03:49:04