Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MultiPartParser in Django Rest Framework

I need to upload a file and some JSON associated with it. But I don't understand how to save the different parts, specifically the JSON part i.e. I'm able to save the image but not the JSON.

I read that I need to use a MultiPartParser but I can't figure out how to integrate it correctly into my serializer class.

Here is the multi-part request that my Server is receiving:

<QueryDict: {'geo': ['{"point" : { "type:" : "Point", "coordinates" : [11.51350462236356, -22.70903491973877]}}'], 'picture': [<TemporaryUploadedFile: photo3.jpg (image/*)>]}>

Here is the view:

class UserUploadedPicture(APIView):

    def post(self, request, format=None):
        print(request.data)
        print("\n\n\n")
        serializer = PictureSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

Here is the serializer:

class PictureSerializer(GeoFeatureModelSerializer):
    class Meta:
        model = Pictures
        geo_field = "point"
        fields = ('picture', 'processed', 'flagged', 'point')

Here is the model:

class Pictures(models.Model):
    objects = models.GeoManager()
    picture = models.ImageField(null=True, default=None, blank=True)
    processed = models.BooleanField(default=False)
    flagged = models.BooleanField(default=False)
    point = models.PointField(null=True, default=None, blank=True)

Can anyone please tell me how to serialize the point field correctly? Maybe I need to change the JSON format? Maybe I need to change the serializer?

like image 384
Jenia Ivanov Avatar asked Oct 27 '17 00:10

Jenia Ivanov


People also ask

What is the use of Python parser in Django rest?

Parsers in Django REST are used to parse the content of incoming HTTP request. In HTTP request we receive the data as a string format. Parsers will parse the HTTP contents in to python data types based on the Content-Type header received in the HTTP request.

What is a parser in REST framework?

REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.

How do I implement a custom parser in Django?

See the Django documentation for more details. To implement a custom parser, you should override BaseParser, set the .media_type property, and implement the .parse (self, stream, media_type, parser_context) method. The method should return the data that will be used to populate the request.data property.

Do I need to use formparser and multipartparser together?

You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data. Parses multipart HTML form content, which supports file uploads. Both request.data will be populated with a QueryDict.


1 Answers

As to integrating the MultiPartParser, it is done with the View, since it is responsible of receiving the request and handling it, not the Serializer. You are using a class-based view and defining the parser is done using the parser_classes attribute as explained in the same link to the official documentation you provided.

So your View becomes:

class UserUploadedPicture(APIView):
    parser_classes = (MultiPartParser, )

    def post(self, request, format=None):
        print(request.data)
        print("\n\n\n")
        serializer = PictureSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)

And concerning your Serializer for the PointField, check this SO answer

like image 163
Anas Tiour Avatar answered Oct 12 '22 23:10

Anas Tiour