download file in django

How to Download File in Django

Django is a popular web development framework for python. Sometimes you may want to add the ability to download file in your Django-based website or application. In this article, we will learn how to setup file downloads in Django.


How to Download File in Django

Here are the steps to setup file downloads in Django.


1. Create Django App

Open terminal/command prompt to create a Django app. If you have already created an app, you can skip this step.

$ python3 manage.py startapp filedownload

Create a superuser who has admin rights on your Django app. If you already have a superuser, you can skip this step.

$ python3 manage.py createsuperuser


2. Install the App

Open settings.py in text editor.

$ sudo vi settings.py

Add the above app in INSTALLED_APPS as shown below.

INSTALLED_APPS = [
    …..
    'filedownload'
]


3. Create Templates

Add Templates folder that points to the location of Django templates that will contain the download link to file. If you already have created another folder for all the templates and specified it in settings.py, you can skip this step.

TEMPLATES = [
    {
….
            'DIRS': ['/home/ubuntu/project/filedownload/templates'],
             ….
      },
]


4. Add URL

Open urls.py file in your new app.

$ sudo vi /home/ubuntu/projects/filedownload/urls.py

Add the following code to it to create a new URL path /download to your website/application.

# Import path module
from django.urls import path
# Import views
from filedownload import views

# Set path for download
urlpatterns = [
    path('download/', views.download_file),
]


5. Create View

Now we need to add the URL handler for the above URL. Open views.py file for the filedownload app in a text editor.

$ sudo vi /home/ubuntu/projects/filedownload/views.py

Add the following lines to create a URL handler view.

# Import mimetypes module
import mimetypes
# import os module
import os
# Import HttpResponse module
from django.http.response import HttpResponse


def download_file(request):
    # Define Django project base directory
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # Define text file name
    filename = 'test.txt'
    # Define the full file path
    filepath = BASE_DIR + '/filedownload/Files/' + filename
    # Open the file for reading content
    path = open(filepath, 'r')
    # Set the mime type
    mime_type, _ = mimetypes.guess_type(filepath)
    # Set the return value of the HttpResponse
    response = HttpResponse(path, content_type=mime_type)
    # Set the HTTP header for sending to browser
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    # Return the response value
    return response

In the above code, we have set file folder to be /filedownload/Files and filename to be test.txt. You can change file name and path as per your requirement. In this case, the file downloaded if any user specifies the filename after the home URL, followed by /download. For example, http://www.mysite.com/download

To test it, run Django server.

$ sudo python manage.py runserver

Open browser and go to http://www.mysite.com/download. You will see a download dialog box.


6. Update Template

If you want to download the file via template, just add the hyperlink to the file as shown below in any template.

<html>
    <title>Download File</title>
</head>
<body>
<enter>
   <h1>Download File using Django</h1>
   <a href="{% url 'download_file' filename='test.txt' %}">Download PDF</a>
</center>
</body>
</html>

In this case, you need to modify the views.py function download_file to include a request argument called filename.

# Import mimetypes module
import mimetypes
# import os module
import os
# Import HttpResponse module
from django.http.response import HttpResponse
# Import render module
from django.shortcuts import render

# Define function to download pdf file using template
def download_file(request, filename=''):
    if filename != '':
        # Define Django project base directory
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        # Define the full file path
        filepath = BASE_DIR + '/filedownload/Files/' + filename
        # Open the file for reading content
        path = open(filepath, 'rb')
        # Set the mime type
        mime_type, _ = mimetypes.guess_type(filepath)
        # Set the return value of the HttpResponse
        response = HttpResponse(path, content_type=mime_type)
        # Set the HTTP header for sending to browser
        response['Content-Disposition'] = "attachment; filename=%s" % filename
        # Return the response value
        return response
    else:
        # Load the template
        return render(request, 'file.html')

In the above code, if the filename is empty, then Django will load file.html template, else it will return test.txt file for download. You can use the same method for downloading PDF files or other types of files too. Just update the hyperlink in file.html to specify the PDF filename with extension. Alternatively, you can also fetch the file path from database, if you want.

In this article, we have learnt how to download file in Django. You can modify these steps as per your requirement.

Also read:

How to Check if File Exists in Python
How to Allow MySQL User from Multiple Hosts
How to Check Python Package Dependencies
How to Check Python Package Path
How to Take Screenshot in Ubuntu Terminal

Leave a Reply

Your email address will not be published. Required fields are marked *