I would like to provide a download folder under following URL: https://myapp.eu.pythonanywhere.com/download
For this, I have created a new app: python manage.py startapp servedownload and added following url.py and views.py:
from django.shortcuts import render
import os
from django.http import FileResponse, Http404
def download_folder(request):
# Set the file path to the directory you want to serve for download
folder_path = '/home/myapp/webinterface/download'
# Get a list of all the files in the directory
files = os.listdir(folder_path)
# Render the template with the list of files
return render(request, 'download_folder.html', {'files': files})
def download_file(request, filename):
# Set the file path to the directory you want to serve for download
folder_path = '/home/myapp/webinterface/download'
# Build the full file path
file_path = os.path.join(folder_path, filename)
# Check if the file exists, and raise a 404 error if it doesn't
if not os.path.exists(file_path):
raise Http404('File not found')
# Serve the file as a downloadable response
response = FileResponse(open(file_path, 'rb'), as_attachment=True)
return response
I have also added the urls properly in urls.py:
path('download/', servedownload.download_folder, name='download_folder'), path('download/<str:filename>/', servedownload.download_file, name='download_file'),
The content of download_file.html is:
{% extends 'base.html' %}
{% block content %}
<h1>Download folder contents:</h1>
<ul>
{% for file in files %}
<li><a href="{% url 'download_file' filename=file %}">{{ file }}</a></li>
{% endfor %}
</ul>
{% endblock %}
I can download a specific file but when entering /download it redirects me to my logged in page.