How to make any Django model's file downloadable?

PythonServer Side ProgrammingProgramming

You can use the django-downloadview package to make any file that you have in your project downloadable. You can host the files on a server.

In this article, we will see how to make a file downloadable in our Django project. It will be a fun topic and you will love it.

First, install the package −

pip install django-downloadview

Now create a Django project and an app. Set up urls and do some basic stuff like adding app in INSTALLED_APPS. Also set up MEDIA_ROOT and MEDIA_URL in


In, add the following lines −

from django.db import models

# Create your models here.
class Data(models.Model):

Here, we created a model which will save the file reference of uploaded files. Create some dummy data for this model.


from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django_downloadview import ObjectDownloadView
from .models import Data
download = ObjectDownloadView.as_view(model=Data, file_field=

urlpatterns = [
   path('', views.home,name="home"),
   path('download//', download, name="default"),

urlpatterns += static(settings.MEDIA_URL,

We created two URL endpoints, one is to render the frontend, and the other is the one which has model downloadview. ObjectDownloadView is the instance that takes the model whose file we are going to host and we defined the field which will have the file stored.


def home(request):
   return render(request,'home.html')

Here we rendered our frontend html.

In home.html, add the following code −

<!DOCTYPE html>
      <a href="">
Download</a> // '1' is ID of a dummy data of our 'Data' model

Here we gave reference to a file which we created as dummy data. '1' is the id of our model instance which will have the file stored in it.

You can make links dynamic but here, we want to keep it at a basic level.


Published on 26-Aug-2021 12:04:43