Django ファイルダウンロード機能 実装方法【簡単解説】

Djangoでファイルのダウンロード機能を実装するには、次の手順に従うことができます。

  1. views.pyファイルにダウンロードリクエストを処理するためのビュー関数を作成します。
from django.http import FileResponse
import os

def download_file(request, file_path):
    file_path = os.path.join(settings.MEDIA_ROOT, file_path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as f:
            response = FileResponse(f)
            response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(file_path)
            return response
    else:
        # 文件不存在的处理逻辑
        return HttpResponse("File not found", status=404)
  1. urls.pyファイルでそのビュー関数のURLルートを設定します。
from django.urls import path
from . import views

urlpatterns = [
    path('download/<str:file_path>/', views.download_file, name='download_file'),
]
  1. テンプレートファイルにダウンロードリンクを追加して、そのビュー関数を呼び出す。
<a href="{% url 'download_file' file_path %}">Download File</a>

このようにすると、リンクにアクセスするとファイルのダウンロードが開始され、ブラウザーがファイルのダウンロードダイアログを表示し、ユーザーがファイルを保存するか直接開くか選択できます。

bannerAds