使用Heroku处理Django媒体文件

15

在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)

感谢


你还没有提供任何有关你如何尝试提供这些文件的信息。 - Daniel Roseman
2个回答

17

原因

Heroku在dynos上运行您的应用程序,如果没有请求,则30分钟后dynos会进入睡眠状态,这使得Heroku无法在dynos重新启动之间保留用户上传的媒体文件。

解决方案

使用Amazon S3服务来存储和提供媒体文件,您还可以从S3中提供静态文件。有关文档,请参阅此处.


3
当有不需要注册其他东西的解决方案时,指向第三方解决方案不应该被接受作为答案。 - Neil

9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接