2

The create function is giving me the following error:

AttributeError: 'dict' object has no attribute 'user'

Looks like request.user does not exist in this serializer. Is there a way to retrieve the user id in serializer? Or is this not possible?

class EmployeeQuestionSerializer(serializers.ModelSerializer):

    class Meta:
        model = EmployeeQuestion
        fields = (
            'id',
            'employee',
            'question',
            'attempted',
            'passed',
        )

    def create(self, request):
        serializer = EmployeeQuestionSerializer(employee=request.user.pk)
        if serializer.is_valid():
            return serializer.save();

    def update(self, instance, validated_data):
        instance.attempted = validated_data.get('attempted')
        instance.passed = validated_data.get('passed')
        instance.save()
        return instance
2
  • create has no request parameter, it only has a dictionary with data. Commented Jul 22, 2020 at 20:15
  • request.user is available in your serializer.context stackoverflow.com/questions/63039105/… Commented Jul 22, 2020 at 20:39

1 Answer 1

5

You can to pass the request object from views.py to this serializer

serializer = EmployeeQuestionSerializer(queryset, context={'request':request})

then in serializers.py you can access that with self inside create: user=self.context['request'].user

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Actually the first part isn't necessary, "self.context['request'].user.pk" works right away!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.