0

When I am creating an blog post I also want to automatically save the current user without selecting the user manually as a blog author.

here is my code:

models.py:

class Blog(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    blog_title = models.CharField(max_length=200, unique=True)

serializers.py

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog

views.py

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all().order_by('-id')
    serializer_class = BlogSerializer
    pagination_class = BlogPagination
    lookup_field = 'blog_slug'

    def get_permissions(self):
        if self.action == 'retrieve':
            permission_classes = [IsOwnerOrReadOnly]
        elif self.action == 'list':
            permission_classes = [IsOwnerOrReadOnly]

        else:
            permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup]
        return [permission() for permission in permission_classes]
boyenec
  • 1,405
  • 5
  • 29
  • Does this answer your question? [Return the current user with Django Rest Framework](https://stackoverflow.com/questions/15770488/return-the-current-user-with-django-rest-framework) – Sunderam Dubey Nov 26 '22 at 09:08

1 Answers1

0

You can modify your serializer like below. It picks up the user from the request context and creates the blog.

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog
        fields = "__all__"
        read_only_fields = ["author"]

    def create(self, validated_data):
        user = self.context["request"].user
        blog = Blog.objects.create(**validated_data, author=user)

        return blog
Sam
  • 86
  • 2
  • 10