1

i am using django rest framework for my project.

i have a gallery model which has a user field. this field is a Foreign key to the user that created the gallery. and a name field which is gallery's name.

class Gallery(models.Model):
    user = models.ForeignKey(User,related_name='galleries')
    name = models.CharField(max_length=64)

here is my serializer:

class GallerySerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')

    def validate_name(self, name):
        if len(name) < 3:
            raise serializers.ValidationError("name must at least 3 letters")
        return name
    class Meta:
        model = Gallery
        fields = ('id', 'user', 'name',)

    def create(self, validated_data):
        """
        Create and return a new `Gallery` instance, given the validated data.
        """
        return Galleries.objects.create(**validated_data)

and here is my views:

class GalleryList(generics.ListCreateAPIView):
    queryset = Gallery.objects.all()
    serializer_class = GallerySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user, )


class GalleryDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Gallery.objects.all()
    serializer_class = GallerySerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

i want to validate post (and put) data, and prevent user from creating two gallery with the same name.(if "user A" has a "gallery A", he can't make a gallery with the same name or rename another gallery to "gallery A". but "user B" is allowed to make a "gallery A")

to do so, i need to check if user.galleries.filter(name=name) exist or not.

but i don't know how to get user in serializer.

2
  • excuse my ignorance: isn't the user passed to the create method in the serializer as part of the validated data? Commented Sep 12, 2015 at 20:10
  • yes. but i wanted user in validate_name function. Commented Sep 13, 2015 at 8:05

1 Answer 1

2

You get it from the context that was passed to the serializer. This is done automatically for you, so you can access it like that:

user = self.context['request'].user

If you want to have the ability to specify another user, you can add it to the context yourself:

# This method goes in your view/viewset
def get_serializer_context(self):
    context = super().get_serializer_context()
    context['user'] = #whatever you want here
    return context

That would make the user available as self.context['user']. This is a bit more verbose, but it is more versalite as it allows the serializer to be passed a user different from the one who did the request.

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

1 Comment

thanks. that did the job and adding new objects to context part was very useful.

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.