from django.views.generic import View from django.core.exceptions import ObjectDoesNotExist from django.core.files.storage import default_storage from django.http.response import Http404, HttpResponse from django.utils.encoding import escape_uri_path class LessonPDFView(View): def get(self, request, lesson_id, *args, **kwargs): from university.models import Lesson try: lesson = Lesson.objects.get(pk=lesson_id) if not lesson.pdf: raise Http404 _file = default_storage.open(lesson.pdf.path) # filename = escape_uri_path('{}-附件.pdf'.format(lesson.title)) response = HttpResponse(_file, content_type=lesson.pdf.extension) # response['Content-Disposition'] = "attachment; filename={}".format(filename) return response except ObjectDoesNotExist: raise Http404