How can modify request.data in django REST framework

I am using Django REST Framework

request.data = '{"id": "10", "user": "tom"}'

I want to add extra attribute like "age": "30" before sending it to further like

    request.data = new_data
    response = super().post(request, *args, **kwargs)

I have two issues

  • Why request.data is coming as string rather than dict
  • How can i update the request.data

  • It looks like a json string. To convert it to a dict you should do:

    import json
    data = json.loads(request.data)
    

    then you can add extra attributes:

    data['age'] = 30
    

    Then you will have to make a new request because it seem like you cant just change the old one. This assumes that you are posting to /notes/:

    from rest_framework.test import APIRequestFactory
    factory = APIRequestFactory()
    request = factory.post('/notes/', data, format='json')
    

    一位好朋友刚刚以比我上面说明的更简单的方法带我去上学

    class CreateSomething(CreateAPIView):
        model = Something
        queryset = Something.objects.all()
        serializer_class = SomethingSerializer
    
        perform_create(self,serializer):
        def perform_create(self,serializer):
            ip = self.get_ip()
            ## magic here: add kwargs for extra fields to write to db
            serializer.save(ip_addr=ip)
    
        def get_ip(self):
            x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR',None)
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = self.request.META.get('REMOTE_ADDR',None)
            return ip
    
    class SomethingSerializer(serializers.ModelSerializer):
        email = serializers.EmailField(validators=[UniqueValidator(queryset=Something.objects.all())])
        fieldA = serializers.CharField()
        fieldB = serializers.CharField()
    
        class Meta:
            model = Customer2
            fields = ['email','fieldA','fieldB','ip_addr']
            read_only_fields = ['ip_addr']
    

    According to your comment:

    "because before posting i need to chnage the field names aqs required by the API"

    You should be using the Field 's source argument instead.

    This will make error messages more consistent otherwise your user will face errors with field names they didn't provide.

    链接地址: http://www.djcxy.com/p/30478.html

    上一篇: 如何在android中测试LayoutInflater.from()的这一行

    下一篇: 如何在django REST框架中修改request.data