Как загрузить файл из корневой папки media на телефон или компьютер

Когда я нажимаю на ссылку загрузки mp3 файлов или изображений, вместо того, чтобы они начали загружаться, они просто начинают просматриваться в браузере. Я хочу, чтобы когда я нажимаю на url "http://localhost:8000/s/download_rdr/1/" и файл "http://localhost:8000/s/media/music.mp3" начинает скачиваться, но все, что он делает, это начинает проигрываться в браузере. Мой views.py

    class DownloadRdr(TemplateView):
   
   def get(self, request, pk, *args, **kwargs):
     
      item = Item.objects.get(id=pk) 
       
        
         #Return an mp3
      return redirect('http://localhost:8000/s/media/music.mp3')

Я разобрался, вот полный код:

class DownloadRdr(TemplateView):
   
   def get(self, request, pk, *args, **kwargs):
      if request.user.is_authenticated:
        item = Item.objects.get(id=pk) 
        #order data check
        orderDataCheck = OrderData.objects.filter(item=item, user=request.user)
        orderDataCheck_count = orderDataCheck.count()
        if orderDataCheck_count > 0:
         #Return an mp3
         image_buffer = open(item.upload_file.path, "rb").read()
         response = HttpResponse(image_buffer)
         response['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(item.upload_file.path)
         return response
           
         #return redirect(item.upload_file.url)
        else :
           return HttpResponse('<h4>Error, You do not have access to this product!</h4>')
      else:
         return redirect('accounts:login_page')  

Попробуйте использовать FileResponse, как сказано в документации: https://docs.djangoproject.com/en/3.2/ref/request-response/#fileresponse-objects

from django.http import FileResponse

def get(self, request, pk, *args, **kwargs):
    ...
    response = FileResponse(open(YOUR_FILE_PATH, 'rb'), as_attachment=True)
    return response
Вернуться на верх