samad montazeri
samad montazeri

Reputation: 1273

accessing user in django rest framework

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.

Upvotes: 1

Views: 78

Answers (1)

spectras
spectras

Reputation: 13542

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.

Upvotes: 2

Related Questions