[英]How to serve files for download in django?
I know that derivatives of this question have already been asked. 我知道已经问过这个问题的派生词了。 But those questions are outdated and I would like to hear some new answers for new versions.
但是这些问题已经过时了,我想听听新版本的一些新答案。
I have a model and it has a file field in it. 我有一个模型,并且其中有一个文件字段。
class MyModel(models.Model):
field = models.FileField()
I can upload files with this model by using the admin panel of django and I can set its location with the MEDIA_ROOT
settings variable. 我可以使用django的管理面板使用此模型上传文件,并可以使用
MEDIA_ROOT
设置变量设置其位置。 But I can't download this file in the view. 但是我无法在视图中下载此文件。 I have tried given its URL but I usually get the "404 not found" error.
我已尝试给出其URL,但通常会收到“找不到404”错误。
def download(request):
file = # code to get the the model instance.
context = {'file': file}
return render(request, template, context)
Here is the code in template: 这是模板中的代码:
<a href="{{file.field.url}}">Download Link</a>
This throws a 404 error. 这将引发404错误。 I know why it throw this error.
我知道为什么会引发此错误。 Because no url deffinitions exist for that url.
因为该URL不存在URL定义。
So, how can I download this file? 那么,如何下载此文件?
Django 1.8.7, Python 3.4.3, ubuntu 14.04 Django 1.8.7,Python 3.4.3,Ubuntu 14.04
In development, you can do this to get MEDIA_URL
active 在开发中,您可以执行此操作以激活
MEDIA_URL
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.