4👍
✅
By default, the ModelViewSet
returns the newly created serialized model in response to a POST
request.
If you want all requests to have a different structure that the serialized model, check Niranj’s solution. However, if you need a specific response structure for this request only, you will need to override your view’s .create()
method:
class UserViewSet(viewsets.ModelViewSet):
...
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
# Define how would you like your response data to look like.
response_data = {
"success": "True",
"message": "Successfully sent",
"user": serializer.data
}
return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)
0👍
I guess you need to give metadata on how your our json response must be. Please check this http://www.django-rest-framework.org/api-guide/metadata/ more information
- [Django]-Getting a circular import error in django urls
- [Django]-Is there a way to update the database with the changes in my models?
- [Django]-Lower() in django model
- [Django]-Is there a Django template tag that will convert a percentage to a human readable format?
- [Django]-How to add class attribute to ModelForm
0👍
Use data as dict. and now update it with your user data
data = {
"success": "True",
"message": "Successfully sent",
#serializer.data or anything that return user data dict
"user": serializer.data
}
- [Django]-Error in django interactive shell on pydev eclipse
- [Django]-Django Server Does not affect view changes
- [Django]-Custom metrics from celery workers into prometheus
Source:stackexchange.com