Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  1. Why request.data is coming as string rather than dict
  2. How can i update the request.data
like image 280
John Kaff Avatar asked Nov 22 '15 23:11

John Kaff


People also ask

What is request data in Django?

Django REST framework introduces a Request object that extends the regular HttpRequest, this new object type has request. data to access JSON data for 'POST', 'PUT' and 'PATCH' requests. However, I can get the same data by accessing request. body parameter which was part of original Django HttpRequest type object.

How do I handle requests in Django?

Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function.

How do you pass extra context data to Serializers in Django REST framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.


2 Answers

In case your API is APIView then you should use update function to expand your request data object without losing the data sent from the client-side.

request.data.update({"id": "10", "user": "tom"}) 
like image 150
Ibrahim Tayseer Avatar answered Sep 20 '22 15:09

Ibrahim Tayseer


request.data should be an immutable QueryDict, rather than a string. If you need to modify it:

if isinstance(request.data, QueryDict): # optional     request.data._mutable = True request.data['age'] = "30" 

The only reason you might check if it's an instance of QueryDict is so it's easier to unit test with a regular dict.

like image 27
mikebridge Avatar answered Sep 17 '22 15:09

mikebridge