0

I'm new to Django Rest Framework,running v. 3.5.4 (Django 1.10.6) and I have implemented a simple model (Test) and its ModelSerializer.

This model has a manyTomany relationship with another one, but this is not the problem right now. The thing is that I need to pass an array of ids from my ajax call, to add to my manytomany relationship.

Ajax call is like this:

data = {
     address: 'foo'
     owner: [1,2]
}

ajax = $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "json",
    success: function(res){
        console.log(res)
    },
    error: function(error) {
        console.log(error,'erro')
    }
 }) 

My view is like this:

class Test(APIView):


    def post(self, request, format=None):

        print(request.data)
        print([(x,y) for x,y in request.data.items()])

        serializer = TestSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

So, the print outputs from my view are the problem:

Output from print(request.data) is <QueryDict: {'address': ['foo'], 'owner[]': ['1', '2']}>

So far so good!

Output from print([(x,y) for x,y in request.data.items()]) is [('address', 'foo'), ('owner[]', '2')]

Whaaaaat?

So, the array became a string with the last item only. What happened?

Apart from that, the is.valid() method seems to erase the array. I made a custom create method in my serializer:

class TestSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
owner = OwnerSerializer(many=True)
class Meta:
    model = Test
    fields = ('id','address','owner')


def create(self, validated_data):
    print(validated_data)

    return none

Output from print is {'address': 'foo', 'owner': []} And no error raised!

So, what is going on here?

Thanks!

2 Answers 2

1
@list_route(methods=['POST'], permission_classes=[AllowAny])
def test(self, request):
    print(request.data)
    print([(x, y) for x, y in request.data.items()])
    print(request.data['owner'])
    import ast
    for x in ast.literal_eval(request.data['owner']):
        print(x)
    return Response("...")

<QueryDict: {'address': ['foo'], 'owner': ['[1,2]']}>
[('address', 'foo'), ('owner', '[1,2]')]
[1,2]
1
2

Ajax try:

data = {
 address: 'foo'
 owner: '[1,2]'
}
Sign up to request clarification or add additional context in comments.

Comments

0

I have the same problem, i solved this problem providing

serializer = TestSerializer(data=request.data.dict())

instead o f

serializer = TestSerializer(data=request.data)

I supose this inconvenient will be solved in a future release.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.