Django 图像在开发环境中不显示

问题描述 投票:0回答:1

我正在尝试使用图像字段在模型中添加图像

文件夹结构:

/base
    /migrations
    /tempelates
    ...
    admin.py
    models.py
    urls.py
    ...
/env
/static
    /images
        avatar.png
    /styles
    /png
/networth_tracker/
/tempelates/
db.sqlite3
manage.py
pp1.jpg  #image I uploaded from admin site
pp2.jpg  #image I uploaded from admin site
pp3.jpg  #image I uploaded from admin site

/base/models.py

class Account(models.Model):
    ...
    logo = models.ImageField(null=True,default="avatar.png")
    ....

    class Meta:
        ordering = ['-updated', '-created']

    def __str__(self):
        return self.name

/networth_tracker/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('base.urls')),
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIAFILES_DIRS)

/networth_tracker/settings.py

...
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / "static"]

MEDIA_URL = '/images/'
MEDIAFILES_DIRS = BASE_DIR / "static/images"
...

问题:

  1. 我从管理网站上传图片
  2. 我尝试直接在管理站点中查看图像并收到以下错误 -- 它在 127.0.0.1/images/pp1.jpg 中搜索图像并返回未找到的页面
  3. 图像上传到/(根目录)而不是/static/images/(媒体目录)

我尝试了替代方案,但也不起作用:

  1. 我尝试在 ImageField 中添加 upload_to="static/images" 模型.py
class Account(models.Model):
   ...
   logo = models.ImageField(null=True,default="avatar.png", upload_to="static/images")
   ...
    
   class Meta:
        ordering = ['-updated', '-created']

    def __str__(self):
        return self.name

  1. 它将图像上传到 static/images/ 文件夹,但出现以下错误
python django django-admin
1个回答
0
投票

MEDIAFILES_DIRS
- 没有这样的选项。您需要设置
STATIC_ROOT
MEDIA_ROOT

文档

© www.soinside.com 2019 - 2024. All rights reserved.