Home > Software design >  Unable to get current user inside django rest serializer
Unable to get current user inside django rest serializer

Time:11-21

I'm unable to get current user inside serializer. I have passed context but still i get error like

"user": [
        "This field is required."
    ]


#Serializer.py

class AddressSerializer(ModelSerializer):
    class Meta:
        model = Address
        fields = "__all__"

    def create(self, validated_data):
        request = self.context["request"]
        validated_data["user"] = request.user
        return super().create(validated_data)

#Views.py

class AddAddress(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        print(request.user)
        serializer = AddressSerializer(data=request.data, context={"request":request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, 200)
        return Response(serializer.errors)

#Models.py

class Address(models.Model):
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=35)
    email = models.EmailField(max_length=100)
    phone = models.BigIntegerField()
    address_line_1 = models.TextField(max_length=500)
    address_line_2 = models.TextField(max_length=500)
    zip_code = models.IntegerField()
    city = models.CharField(max_length=20)
    state = models.CharField(max_length=15)
    country = models.CharField(max_length=15)

    class Meta:
        verbose_name_plural = "Address"

    def __str__(self):
        return self.full_name


I exactly don't know the problem behind this

CodePudding user response:

You can do this with the save() method

    class AddAddress(APIView):
        permission_classes = [IsAuthenticated]
    
        def post(self, request):
            print(request.user)
            serializer = AddressSerializer(data=request.data, context={"request":request})
            if serializer.is_valid():
                serializer.save(user=request.user)
                return Response(serializer.data, 200)
            return Response(serializer.errors)

CodePudding user response:

Try this:

request = self.context.get('request', None)

instead of this request = self.context["request"]

  • Related