django 2.1休息上传文件并获取网址

时间:2018-10-27 14:27:01

标签: django

我想使用rest框架在django 2.1中上传文件,并将最终URL保存在数据库中。

这是我目前的课程:

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):

        print(request.FILES)

        screenshot_file       = request.FILES["screenshot_file"]
        mouse_event_count     = request.data["mouse_events_count"]
        keyboard_events_count = request.data["keyboard_events_count"]

        try:
            contract = Contract.objects.get(id=contract_id)
        except Contract.DoesNotExist:
            JsonResponse({"message":"contract id does not exist !"}, status=404)

        file_serializer = FileSerializer(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()

        ContractEvent.objects.create(
            title="",
            contract=contract,
            mouse_events_count=mouse_event_count,
            keyboard_events_count=keyboard_events_count,
            screenshot_filename=screenshot_file,
            screenshot_url="https://upload.wikimedia.org/wikipedia/commons/5/57/Bootstrap-3.1.1-screenshot-jumbotron-example.png",
            event_type="log",
            created_date_time=datetime.datetime.utcnow().replace(tzinfo=pytz.utc),
            created_date=datetime.datetime.utcnow().replace(tzinfo=pytz.utc).date()
        )

        return JsonResponse({"message":"log successfully created"}, status=201)

django手册上的所有示例都使用序列化程序功能,问题是..我不想将文件保存在数据库中,我只想上传文件并仅将最终URL保存在数据库中。替换实际的screenshot_url,我该怎么做?

0 个答案:

没有答案