如何在django-heroku中部署媒体文件?

问题描述:

我正在尝试在heroku上部署django应用程序.我目前正在使用软件包 django-heroku 作为标准设置.在我的模型下,一些使用ImageField上传的媒体文件,我希望它们显示在模板中.但是,尽管它们似乎指向了正确的目的地,但并未为他们提供服务.

I am trying to deploy a django app on heroku. I'm currently using the package django-heroku as the standard setup. Under my models some media files that are uploaded using ImageField and I want them to be displayed in my templates. However, although they seem to point to the correct destination they are not being served.

我已经在SO中找到了类似的问题,并在git官方仓库中查找了示例,但是我没有找到使用相同配置的任何示例.

I've looked to similar questions here in SO and looked into the official package git repository looking for examples, however I did not find any example using the same configuration.

settings.py

settings.py

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

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

.
.
.

django_heroku.settings(locals())

模板

{% extends 'base_site.html' %}
{% load i18n %}
{% block content_title %}{% trans 'Manage Product Detail' %}{% endblock%}
{% block content %}

<div class="card">  
  <div class="carousel-inner" role="listbox">
    {% for figure in product.figures.all %}        
        <div class="item{% if forloop.first %} active{% endif %}">                    
              <img src="{{ figure.image.url }}">
        </div>
    {%endfor%}
  </div>
  <div class="card-body">
    <h5 class="card-title">{{ product.name }}</h5>
    <p class="card-text">{{ product.description }}}
  </div>
  <div class="card-footer">
    <h5 class="card-title">{{ product.name }}</h5>
    <p class="card-text">{{ product.description }}}
  </div>
</div>


{% endblock %}

尽管我可以确认媒体文件夹,子文件夹和图像存在(在我的项目的根目录中),并且对象存在于模板中,但仍然出现以下404错误:

Although I can confirm that the media folder, subfolder and image exist (at the root of my project) and that the object is present in the template, I'm still presented with the following 404 error:

Not Found: /media/images/Screenshot_from_2018-12-26_21-07-01.png
[04/Jan/2019 14:32:34] "GET /media/images/Screenshot_from_2018-12-26_21-07-01.png HTTP/1.1" 404 2863

django-heroku软件包无法立即提供此功能(由于heroku方面的限制,无法实现无缝部署和开发)媒体文件).在开发中,必须通过以下方式加载媒体文件:

The package django-heroku would not provide this functionality out-of-the-box (due to restrictions on heroku side it is impossible to achieve seamless deployment and development of media files). In development one must load the media files through:

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

在生产中,静态文件(如上面提到的某些用户)必须从外部来源提供.以下是我目前关注的提示: https://web.archive.org/web/20170607080235/http://djangobook.com/serving-files-production/

In production the static files, as some users referred above must be served from an external source. Here are the tips I'm currently following: https://web.archive.org/web/20170607080235/http://djangobook.com/serving-files-production/