Bora
Bora

Reputation: 1858

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

Upvotes: 0

Views: 718

Answers (1)

itzMEonTV
itzMEonTV

Reputation: 20369

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)

Upvotes: 1

Related Questions