Home > OS >  use validate method to post the data that is assigned to particular user in django rest Framework
use validate method to post the data that is assigned to particular user in django rest Framework

Time:10-12

I have user registration with user and project as foreign key and using serializer I wanted to choose only that project that is assigned to particular user but I can't figure out how to use validate method

So user can choose only that project which is assigned to him in registration process

CodePudding user response:

You can validate and field with validate_fieldname, you can for example do (depending on how the user/project mapping is set up)

class ProjectUserRegistrationSerializer(ModelSerializer):
    ...

    def validate_project(self, value):
        user_id = self.context['request'].user.pk
        if not value.users.filter(pk=user_id).exists():
            raise serializers.ValidationError("You are not welcome in this project.")

And some totally unrelated comments

You probably want the id field (and possibly some others) to be read-only which you do by adding read_only_fields = ('id',) to your Meta class.

context = super(ProjectUserRegistrationViewSet, self).get_serializer_context()

can be simplified to just

context = super().get_serializer_context()

If you are not planning to support python2.

CodePudding user response:

Guessing what the project model looks like.

class ProjectUserRegistrationSerializer(ModelSerializer):
    class Meta:
        model = ProjectUserRegistration
        fields = (
            'id',
            'date',
            'start',
            'start_note',
            'started',
            'started_at_location',
            'end',
            'end_note',
            'ended',
            'ended_at_location',
            'project',
        )

    def validate(self, attrs):
        # validated the data first 
        validated_data = super().validate(attrs)
        # Grab user and project from validated data
        user = validated_data.get("user")
        project = validated_data.get("project")
        if Project.objects.filter(id=project.id, users__in=[user]).exists() == False:
            raise ValidationError("user not added to project")
        return validated_data
  • Related