Django未投放图片

时间:2019-03-29 20:49:26

标签: django python-3.x image django-models

我使用问题View does not seem to be saving all the information in my model中的表格上传的我的媒体正在上传到我定义的正确的/ media / images文件夹中。但是,在访问时返回404。 我尝试按照https://stackoverflow.com/a/39359264上的说明进行操作,但仍然收到404。

我的模板代码

{% for books in object_list %}
    <img src="{{ books.cover_pic.url }}">
{% endfor %}

settings.py

STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

我的urls.py

urlpatterns =[
    path('', views.index, name='index'),
] 
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我的图片模型代码是

cover_pic = models.FileField(null=True, blank=True, upload_to='images/')

我的媒体文件夹位于基本目录(manage.py旁边)。 我在俯视什么?

1 个答案:

答案 0 :(得分:0)

尝试一下。这样对我有用。您还可以尝试一些我在models.py中注释过的方法 任何东西。

settings.py

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

MEDIA_ROOT = (
BASE_DIR
)


MEDIA_URL = '/media/'

models.py ...

#Here you can try changing FileField to ImageField if you like.
# You can also try directory uploads as image without backslash
#cover_pic = models.ImageField(upload_to='images')

cover_pic = models.FileField(upload_to='images/')

urls.py(项目)

if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

模板(.html)

  {% for books in object_list %}
    <img src="{{ books.cover_pic.url }}">
{% endfor %}