将Heroku用于Django媒体文件

时间:2017-01-04 22:16:57

标签: django heroku

在heroku域上,我无法加载媒体(使用ImageField属性保存的图像)文件图像。但是,如果我设置debug = True

,我可以看到保存在静态字段中的图像

我使用以下命令保存图像:

image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field = "height_field")

我可以通过这样的方式在我的模板中引用它们:

<img src="{{ instance.image.url }}" class="img-responsive">

从我的views.py传递实例,如下所示:

instance = get_object_or_404(Post,slug=slug)
if instance.draft or instance.publish > timezone.now().date():
    if not request.user.is_staff or not request.user.is_superuser:
        raise Http404
share_string = quote_plus(instance.content)
context = {
    "title": "Detail",
    "instance": instance,
    "share_string":share_string,
}
return render(request,"post_detail.html",context)

由于

2 个答案:

答案 0 :(得分:6)

的原因

如果没有请求,Heroku会在dynos和dynos上运行你的应用程序30分钟后进入睡眠状态,这使得Heroku不会在dynos restart之间保留用户上传媒体文件。

解决方案

使用Amazon S3服务存储和提供媒体文件+您也可以从S3提供静态文件。有关文档,请参阅here.

答案 1 :(得分:0)

Heroku文件系统是临时的,因此dynos使用最新部署中文件系统的干净副本启动。以下是解决此问题的一些方法:

  1. AWS S3
  2. 如果您不想在AWS上设置帐户来创建S3存储桶,请Heroku has add-ons来处理静态资产的存储和处理

有关此问题的更多详细信息,请参见 https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted