Django built-in code signing provides a secure way to generate temporary download links for files.
The index view creates a signed token (in this example valid for 5 minutes) that encodes the file path and builds a download URL.
The TemporaryDownloadView verifies this token, ensures the file exists, and serves it with FileResponse.
If the token is invalid or the file is missing, a 404 error is returned.
Assume:
mysite/
...
files/
cv.pdf
from django.urls import path
from .views import *
urlpatterns = [
path("", index.as_view(), name="index"),
path("download/<str:token>/", TemporaryDownloadView.as_view(), name="download_temp"),
]
from django.views.generic import TemplateView, View
from django.http import FileResponse, Http404
from django.conf import settings
from django.urls import reverse
from django.core import signing
from pathlib import Path
class index(TemplateView):
template_name = 'polls/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
token = signing.dumps("cv.pdf", salt="download")
download_url = self.request.build_absolute_uri(reverse('download_temp', args=[token]))
context['download_url'] = download_url
return context
class TemporaryDownloadView(View):
def get(self, request, token):
try:
data = signing.loads(token, salt="download", max_age=300)
my_file = Path(settings.BASE_DIR / "files" / data)
if not my_file.exists():
raise Http404("File not found")
except signing.BadSignature:
raise Http404("Invalid or expired token")
return FileResponse(open(my_file , "rb"), as_attachment=True, filename=data)
<a href="{{download_url}}">Download</a>
Django 5.2
05 Oct. 2025
|
Last Updated: 03 Dec. 2025
|
jaimedcsilva Related