I am having some problems with serializer. I'm calling a post method which I want it to call the serializer. Also I want to have the user sent to the serializer. my post method is:
def post(self, request, *args, **kwargs):
serializer = ResourceListSerializer(context={'request': request}, data={})
serializer.is_valid(raise_exception=True)
serializer.save(creator=request.user)
but it does not seem to be getting the data in serializer. in the serializer, self.validated_data seems to be empty. this is the code on the serializer:
def save(self, **kwargs):
"""
Update `project` and `resource_type` fields in database.
"""
resources = self.validated_data.get('resources')
if resources is not None and len(resources) > 0:
self.validated_data['project'] = self.validated_data['resources'][0].project
self.validated_data['resource_type'] = self.validated_data['resources'][0].resource_type
try:
project = self.data.get('project')
return super(ResourceListSerializer, self).save(**kwargs)
except:
try:
project = self.validated_data['project']
return super(ResourceListSerializer, self).save(**kwargs)
except:
raise serializers.ValidationError("Resource List should belong to a Project.")
any suggestion on how to call the serializer properly?
Pass data
when instantiating your serializer, not context
.
def post(self, request, *args, **kwargs):
serializer = ResourceListSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save(creator=request.user)
You only need context
to pass extra context. Unless you have custom code in your serializer that accesses self.context
, you don't need it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.