管理视图中的Django ImageField url不正确

时间:2018-06-19 10:14:28

标签: django media

我有一个模型将图像存储在媒体子目录中,"媒体/游戏/"。图片会上传到正确的位置,但是当我尝试在管理页面中检索图片时,它会尝试在基本媒体/路径中检索它,并且似乎无法进入游戏文件夹,所以如果我看下:

  

本地主机:8000 /媒体/游戏/ image.png

它会显示图像,但如果我在管理员中并点击预览的图片链接,它会尝试在以下位置找到它:

  

本地主机:8000 /媒体/ image.png

不应该是ImageField" games / image.png"而不只是" image.png"?我不认为图像字段正确存储路径。

以下是我的文件:

模型:

from django.db import models
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location="media/games/")

    class Game(models.Model):
        title = models.CharField(max_length=127, unique=True)
        slug = models.SlugField(max_length=127, unique=True)
        summary = models.TextField(null=True, blank=True)
        description = models.TextField(null=True, blank=True)
        release_date = models.DateField('date released', null=True, blank=True)
        released = models.BooleanField(default=False)
        purchase_link = models.URLField(max_length=255, null=True, blank=True)
        card_image = models.ImageField(storage=fs, null=True, blank=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.TimeField(auto_now=True)

        def __str__(self):
            return str(self.title)

URLS:

from django.conf.urls import url, include
from django.contrib import admin
from InvenTorrey.settings import base
from django.conf.urls.static import static

from games import urls as game_urls



urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^^api/v1/', include(game_urls)),
]

if base.DEBUG is True:
    urlpatterns += static(base.MEDIA_URL, document_root=base.MEDIA_ROOT)

设定:

BASE_DIR = 
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
STATIC_ROOT = os.path.join(BASE_DIR,"static/")
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

1 个答案:

答案 0 :(得分:1)

而不是storage参数尝试使用upload_to

card_image = models.ImageField(upload_to='games/', null=True, blank=True)

这样您就可以将图片保存到media/games/目录,还可以将games/添加到图片的网址路径。