django admin圖片上傳回顯

這個(gè)問題其實(shí)就是compute字段如何顯示在django admin的編輯表單中。由于django admin默認(rèn)只會(huì)顯示model中editable=true的屬性,所以計(jì)算字段需要特殊處理。

最開始是在model中直接定義了一個(gè)自定義方法屬性image_data。

class Product(models.Model):
    # ... other fields
    image = models.ImageField(u'圖片', upload_to='photos/%Y/%m/%d')
    def image_data(self, obj):
        return mark_safe(u'< img src="%s" width="100px" />' % obj.image.url)
    # 頁面顯示的字段名稱
    image_data.short_description = u'品牌圖片'

# 在admin.py中定義模型對(duì)應(yīng)的admin展示方式
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'image_data')
    readonly_fields = ('image_data',)  #必須加這行 否則訪問編輯頁面會(huì)報(bào)錯(cuò)

以上這種方式可以在列表中正常顯示上傳的圖片,但是在編輯表單中圖片對(duì)應(yīng)的字段只會(huì)顯示一個(gè)label,內(nèi)容不會(huì)顯示出來。

經(jīng)過google找到解決辦法:

class Product(models.Model):
    # ... other fields
    image = models.ImageField(u'圖片', upload_to='photos/%Y/%m/%d')

# 在admin.py中定義模型對(duì)應(yīng)的admin展示方式
from django.utils.safestring import mark_safe
class ProductAdmin(admin.ModelAdmin):
    list_display = ('name', 'image_data')
    readonly_fields = ('image_data',)  #必須加這行 否則訪問編輯頁面會(huì)報(bào)錯(cuò)
    def image_data(self, obj):
        return mark_safe(u'< img src="%s" width="100px" />' % obj.image.url)
    # 頁面顯示的字段名稱
    image_data.short_description = u'品牌圖片'

看到這里應(yīng)該清楚了吧,其實(shí)很簡(jiǎn)單只要將model中的自定義方法字段移到modelAdmin中即可。
注意:文章中的< img src="%s" width="100px" /> 故意在“<”后多加了空格 否則簡(jiǎn)書的編輯器會(huì)自動(dòng)轉(zhuǎn)義掉,大家寫代碼的時(shí)候要去掉否則會(huì)報(bào)錯(cuò)。(感謝P_sky的提醒)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容