Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling serializer in django rest framework

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?

like image 317
Nicky Mirfallah Avatar asked Mar 30 '26 20:03

Nicky Mirfallah


1 Answers

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.

like image 165
Daniel Hepper Avatar answered Apr 02 '26 04:04

Daniel Hepper