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

Example

In models.py, add the following lines −

from django.db import models

# Create your models here.
class Data(models.Model):
   file=models.FileField(upload_to='myfiles/',blank=True)

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

In urls.py

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=
'file')

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

]
urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)

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.

In views.py

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

Here we rendered our frontend html.

In home.html, add the following code −

<!DOCTYPE html>
<html>
   <head>
      <title>
         TUT
      </title>
   </head>
   <body>
      <h2>HI</h2>
      <a href="http://127.0.0.1:8000/download/1/">
Download</a> // '1' is ID of a dummy data of our 'Data' model
   </body>
</html>

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.

Output

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