我想在Django rest_framework中上传文件,我的当前代码是:
class get_contract_events_log(APIView):
authentication_classes = (BearerTokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
parser_classes = (JSONParser, FormParser, MultiPartParser,)
def post(self, request, contract_id, format=None):
screenshot_file = request.FILES["screenshot_file"]
mouse_event_count = request.data["mouse_events_count"]
keyboard_events_count = request.data["keyboard_events_count"]
contract = Contract.objects.get(id=contract_id)
# file_serializer = FileSerializer(data=request.FILES)
# if file_serializer.is_valid():
# file_serializer.save()
ContractEvent.objects.create(
#....
screenshot_filename=screenshot_file,
screenshot_url="https://upload.wikimedia.org/wikipedia/commons/5/57/Bootstrap-3.1.1-screenshot-jumbotron-example.png",
)
return JsonResponse({"message":"log successfully created"}, status=201)
序列化器:
class FileSerializer(serializers.ModelSerializer):
class Meta():
model = ContractEvent
fields = ('screenshot_file')
我的当前代码返回错误:
TypeError: The `fields` option must be a list or tuple or "__all__". Got str.
[27/Oct/2018 15:04:25] "POST /contracts/3/events/log HTTP/1.1" 500 18899
我如何解决此错误?我需要用上传文件的路径替换screenshot_url。
答案 0 :(得分:1)
您的
class FileSerializer(serializers.ModelSerializer):
class Meta():
model = ContractEvent
fields = ('screenshot_file')
正确
class FileSerializer(serializers.ModelSerializer):
class Meta():
model = ContractEvent
fields = ('screenshot_file',)
add,在“ screenshot_file”之后