diff --git a/src/document/serializers.py b/src/document/serializers.py index 937ecac3ee2630ed9770e7b745174ae9a8663929..f1c209fd1eb1d7f10ea2bbd462edf8a816d01878 100644 --- a/src/document/serializers.py +++ b/src/document/serializers.py @@ -8,6 +8,7 @@ _max_count = 1 class DocumentSerializer(serializers.ModelSerializer): uploaded_by = serializers.HiddenField(default=CurrentUserProfileDefault()) uploaded_by_name = serializers.SerializerMethodField() + file = serializers.SerializerMethodField() class Meta: model = models.Document @@ -30,6 +31,9 @@ class DocumentSerializer(serializers.ModelSerializer): def get_uploaded_by_name(self, obj): return obj.uploaded_by.full_name + def get_file(self, obj): + return f"/api/v1/documents/{obj.id}/download/" + def validate_solution(self, value): profile = self.context['request'].user.profile if value not in profile.solution.all(): @@ -38,7 +42,5 @@ class DocumentSerializer(serializers.ModelSerializer): uploaded_by=profile, solution=value).count() if count >= _max_count: raise serializers.ValidationError( - 'You cant upload more than ' + - str(_max_count) + - ' document to one solution!') + f'You cant upload more than {max_count} document to one solution!') return value diff --git a/src/document/views.py b/src/document/views.py index 1adb1187c5e12e8f7c29cee642a2e412d34fb366..3744e3b7b5507edf625e88cc087ab2b2c8709c61 100644 --- a/src/document/views.py +++ b/src/document/views.py @@ -3,7 +3,9 @@ from common import permissions from . import models from . import serializers from rest_framework.parsers import JSONParser, MultiPartParser - +from django.http import HttpResponse, Http404 +from rest_framework.decorators import action +import os class DocumentViewSet(viewsets.ModelViewSet): serializer_class = serializers.DocumentSerializer @@ -43,3 +45,12 @@ class DocumentViewSet(viewsets.ModelViewSet): } serializer.save(**kwargs) + + @action(detail=True, methods=["get"]) + def download(self, request, pk): + document = self.get_object() + with document.file.open() as fh: + response = HttpResponse(fh.read(), content_type="application/media") + response['Content-Disposition'] = 'inline; filename=' + os.path.basename(document.file.name) + return response + raise Http404