Django:在生产环境中无法加载用户上传的媒体文件

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

我在铁路上托管我的网站。一切都已设置且工作正常,但用户上传的图像未加载。

设置.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
]

MEDIA_URL ='/media/'
MEDIA_ROOT = os.path. join(BASE_DIR,'media')

模型.py

class Post(models.Model):
    img = models.ImageField(upload_to="pics")

博客.html

{% extends 'base.html' %}
{% load static %}

{% static "images/projects" as baseUrl %}

{% for post in post_list %}
 <div class="image_wrapper"><a href="{% url 'post_detail' post.slug %}" target="_parent"><img
                    src="{{ post.img.url }}" alt="image 1"/></a></div>

 {% endfor %}

url.py

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

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

我遇到的错误:

Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
Not Found: /media/pics/CC_Tech_Computers_1_6rgae2m.jpg
django hosting production-environment
1个回答
0
投票

而不是这个:

src="{{ post.img.url }}"

试试这个方法:

src="/media/pics/post.img"

在你的

models.py

img = models.ImageField(upload_to="pics/") #Here added `forward slash (/)`

尝试这种方式,看看是否加载图像

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