0

I am working on a django application in which users can download their own files. I need to make the files secure and only let them download it.

At first, I was thinking of using something like

{%if files%}
<a href='/media/files/pics/photo.png' download>

Then i realised that anyone can brute force my site and get any files. So I thought of handling the download through views. I am very beginner and don't know how to make my own download view. So I used something like:

at views.py

def download(id):
    file = data.objects.get(pk=id)
    url = file.fileurl
    filename = wget.download(url)

and call the function when the user want to download the file. I am using wget module. I think I am doing wrong, So I decided to ask for some suggestions.

At last my question is : Is it wrong to use other modules to download files? Or how to write a download view on Django?

Thank you!!

Utsavkaf
  • 21
  • 6

1 Answers1

0

How to download a file in Django depends on your needs. any library that can download and store the file somewhere should be fine. How to serve them to other users on the other hand is a different story.

As you mentioned, you need URLs to be private so only the authorized user can download the file. In this case, You can set up a view and authorize the user and then let your webserver know that it should serve a specific file to this user.

You can use X-Accel-Redirect if you're using Nginx. Other web servers such as Apache have a similar option named X-Sendfile.

Take a look here for nginx example: Django and Nginx X-accel-redirect

As for saving files, you should save the files somewhere and store the path to that file in the database and link it to a user (with a foreignkey for example) and let only the owner of the file download the file. It is also worth mentioning that downloading files might take a long time so it's a good idea to lunch a background task for downloading the files and allow users to start the download when it's finished. You can take a look at Celery for background tasks.

Navid Zarepak
  • 4,148
  • 1
  • 12
  • 26