如何在Django Rest Framework中加载文件?

时间:2017-01-19 12:04:00

标签: python angularjs django api django-rest-framework

我想在Django Rest Framework中上传文件。我根据django文档向所有人申请。

views.py

class HomeworkUploadView(APIView):

    parser_classes = (FileUploadParser, MultiPartParser)
    serializer_class = HomeworkUploadSerializer
    queryset = DeliveredHomework.objects.all()
    lookup_url_kwarg = 'student'

    def get_queryset(self):
        student = self.kwargs.get(self.lookup_url_kwarg)
        homeworks = DeliveredHomework.objects.filter(student=student)
        return homeworks

    def put(self, request, student, format=None):
        file_obj = self.request.FILES['file']
        print(file_obj)
        if file_obj is None:
                return Response(status=400)

        filename = '{}/{}/{}'.format(MEDIA_ROOT, "homework_evdekikurs", file_obj)
        with open(filename, 'wb+') as temp_file:
                for chunk in file_obj.chunks():
                    temp_file.write(chunk)

        return Response(status=204)

models.py

class DeliveredHomework(TimeStampModel):

    file = models.FileField(
        null=True,
        blank=True,
        upload_to=_handle_homework_file,
    )

我安排了MEDIA_ROOT设置。但是响应是这样的:

tmp_00z2ap.upload 问题是什么?谢谢。

def _handle_homework_file(instance, filename):
    homework = instance.homework
    homework_id = homework.id
    homework_title = slugify(homework.title)

    lecture = homework.lecture
    lecture_id = lecture.id
    lecture_title = slugify(lecture.title)

    unit = lecture.unit
    unit_id = unit.id
    unit_title = slugify(unit.title)

    course = unit.course
    course_id = course.id
    course_title = slugify(course.title)

    name, extension = splitext(filename)
    # username_filename.ext
    new_filename = "{}_{}{}".format(instance.student, slugify(name), extension)


    upload_path = "homeworks/course_{0}/unit_{1}/lecture_{2}/homework_{3}".format(
    course_id, unit_id, lecture_id, homework_id)

    return '{}/{}'.format(upload_path, new_filename)

我的意思是文件已上传到上传路径的位置。

enter image description here

0 个答案:

没有答案