2015-03-25 117 views
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。

謝謝!

回答

0

據我瞭解你是ImagePost模型之間1對1的關係。所以你應該使用OneToOneField而不是兩個ForteignKey

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

而且從Post模型刪除post_image領域。

要從Post訪問圖像實例只是寫:

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

它的工作原理,謝謝! – randomp 2015-03-25 03:49:04