[英]image not displaying in django admin site
我有這個模型:
projectDirPath = path.dirname(path.dirname(__file__))
storeImageDir = FileSystemStorage(location=projectDirPath + '/couponRestApiApp/stores')
class stores(models.Model):
""" This is the store model """
storeName = models.CharField(max_length=15) # Store Name
storeDescription = models.TextField() # Store Description
storeURL = models.URLField() # Store URL
storePopularityNumber = models.IntegerField(max_length=1) # Store Popularity Number
storeImage = models.ImageField(upload_to="images",storage=storeImageDir) # Store Image
storeSlug = models.CharField(max_length=400) # This is the text you see in the URL
createdAt = models.DateTimeField(auto_now_add=True) # Time at which store is created
updatedAt = models.DateTimeField(auto_now=True) # Time at which store is updated
storeTags = models.ManyToManyField(tags) # All the tags associated with the store
def __unicode__(self):
return unicode(self.storeName)
def StoreTags(self):
return '\n'.join([s.tag for s in self.storeTags.all()])
def StoreImage(self):
return '<img src="%s" height="150"/>' % (self.storeImage)
StoreImage.allow_tags = True
但是圖像沒有加載到管理頁面上,圖像 URL 是: http://localhost:8000/admin/couponRestApiApp/stores/static/mcDonalds.jpg/
正在顯示,但正確的路徑應該是: /home/vaibhav/TRAC/coupon-rest-api/couponRestApi/couponRestApiApp/stores/static/mcDonalds.jpg/
圖像必須存儲在哪里才能顯示在 Django 管理頁面上
在您的設置中正確定義MEDIA_ROOT
和MEDIA_URL
。
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media').replace('\\','/')
MEDIA_URL = '/media/'
storeImage = models.ImageField(upload_to="images")
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': False}),
)
嘗試使用上面的代碼。
回答評論中提出的問題:
's' 被添加到模型名稱中,因為會有多個模型實例。 要擺脫它,請為模型定義verbose_name
。
class stores(models.Model):
.....
storeName = models.CharField(max_length=15)
.....
class Meta:
verbose_name = 'Store'
verbose_name_plural = 'Stores'
根據 Django 文檔,對於 Django 1.11 及更高版本,您需要重寫:
網址.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
在您的 HTML 代碼中調用全局 url,例如 {{name.store.url}} 它應該在您的 HTML 代碼上完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.