我有这个HTML模板
<html><body>
<form method="POST">
{% render_form submitSerializer %}
<input type="submit" value="Save">
</form>
</body></html>
此序列化程序
class SubmitSerializer(serializers.ModelSerializer):
submittedFile = serializers.FileField()
class Meta:
model = Submit
fields = {'submittedFile', 'result'}
read_only_fields = {'result'}
和这个观点
class SubmitView(APIView):
renderer_classes = [renderers.TemplateHTMLRenderer]
def get(self, request, *args, **kwargs):
return Response({'submitSerializer':submitSerializer}, template_name='singlelesson.html')
def post(self, request, *args, **kwargs):
submit = Submit(lesson=lessonInstance, user=self.request.user, submittedFile = self.request.data['submittedFile'])
serializer = SubmitSerializer(submit)
#compare_files returns true if two files contain same text
result = compare_files(correct_solution, self.request.POST.get('submittedFile'))
serializer.save(result = result)
return Response({'submitSerializer':serializer}, template_name='singlelesson.html')
问题是表单上传的不是文件而是其名称,比较两个文件时出现类型错误。如何让表单上传文件?
答案 0 :(得分:2)
您应该从请求对象中的FILES QueryDict中提取文件,而不是POST。 e.g:
self.request.FILES['submittedFile']
或者django-rest-framework方式:
request.data['submittedFile']
有关详细说明,请查看: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
编辑:同时将表单更改为:
<html><body>
<form method="POST" enctype="multipart/form-data">
{% render_form submitSerializer %}
<input type="submit" value="Save">
</form>
</body></html>
并将SubmitView发送至:
class SubmitView(APIView):
parser_classes = (MultiPartParser,)
...