简体   繁体   中英

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. 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.

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. I know why it throw this error. Because no url deffinitions exist for that url.

So, how can I download this file?

Django 1.8.7, Python 3.4.3, ubuntu 14.04

In development, you can do this to get MEDIA_URL active

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM