0

我有这个模型:

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 管理页面上

4

3 回答 3

5

正确定义MEDIA_ROOTMEDIA_URL在您的设置中。

设置.py

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/'

模型.py

storeImage = models.ImageField(upload_to="images")

网址.py

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'
于 2013-04-16T06:43:36.643 回答
2

根据 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)
于 2018-09-20T03:45:09.750 回答
0

在您的 HTML 代码中调用全局 url,例如 {{name.store.url}} 它应该在您的 HTML 代码上完成

于 2020-07-17T17:13:09.117 回答