Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get authenticated user on serializer class for validation

I'm working on a project using django-rest-framework. In my API view, an authenticated user can create other users. But, only five. Then if there are five users registered by one user, I want to send him in the response that hit the limit. Then, I need to get on my serializer the authenticated user but, I can't find a way to pass it from my ModelViewSet to my serializer.

This is my code:

View:

class ChildUserViewSet(viewsets.ModelViewSet):
    serializer_class = ChildUserSerializer
    queryset = User.objects.all()

    authentication_classes = (
        TokenAuthentication,
    )
    permission_classes = (
        IsAuthenticated,
    )

    def perform_create(self, serializer):
        account_group = self.request.user.userprofile.get_account_group

        mobile_number = serializer.data.get('mobile_number')
        password = serializer.data.get('password')
        user = serializer.save()
        user.set_password(password)
        user.save()

        # Generate user profile
        UserProfile.objects.create(
            user=user,
            mobile_number=mobile_number,
            user_type=CHILD,
            related_account_group=account_group,
        )

Serializer:

class ChildUserSerializer(serializers.ModelSerializer):
    mobile_number = serializers.CharField()

    class Meta:
        model = User

        fields = (
            'first_name',
            'last_name',
            'email',
            'password',
            'mobile_number',
        )

    def validate(self, data):
        """
        Check that the start is before the stop.
        """
        # Get authenticated user for raise hit limit validation



    def validate_email(self, value):
        if User.objects.filter(email=value):
            raise serializers.ValidationError("This field must be unique.")
        return value

    def create(self, validated_data):
        username = generate_unique_username(
            u'{0}{1}'.format(
                validated_data['first_name'],
                validated_data['last_name'],
            )
        )

        user = User(
            username=username,
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
            email=validated_data['email'],
        )

        user.set_password(validated_data['password'])
        user.save()

        return user

Then, in the def validate(self, data) function of my serializer, I want to get the currently authenticated user.

How can I pass the request.user from my APIView to my serializer?

like image 808
Andrés Quiroga Avatar asked Apr 08 '15 20:04

Andrés Quiroga


People also ask

How do I know if my serializer is valid?

We can validate the serializer by calling the method " is_valid() ". It will return the boolean(True/False) value. If the serializer is not valid then we can get errors by using the attribute "errors".

How does Django validate data in serializer?

Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class. With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class.

What does authentication credentials not provided mean?

Simply log out and log back in. Written by Valerie. The underlying cause of this issue can be different things but it essentially means that your browser is not authorized to complete the task you are trying to accomplish.

What does serializer Is_valid do?

is_valid perform validation of input data and confirm that this data contain all required fields and all fields have correct types. If validation process succeded is_valid set validated_data dictionary which is used for creation or updating data in DB.


2 Answers

In your views when you initialize serializer like

serializer = ChildUserSerializer(data=request.DATA,context={'request':request})

,send a context which contains request.Then in Serializers inside function call

request=self.context['request']

Then you can access request.user.

like image 108
Zealous System Avatar answered Oct 01 '22 23:10

Zealous System


You can pass additional context to your serializer with serializer = ChildUserSerializer(data, context={'request': request}). You can then access the authenticated user via request.user within your serializer validation method.

like image 36
axelcdv Avatar answered Oct 01 '22 23:10

axelcdv