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
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.
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.
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.
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"})
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With