Django Rest创建新博客时如何保存当前用户?

ktecyv1j  于 2022-12-01  发布在  Go
关注(0)|答案(1)|浏览(132)

当我创建博客帖子时,我还希望自动保存当前用户,而不是手动选择用户作为博客作者。
下面是我代码:

型号.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)

序列化程序.py

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

查看次数.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]
w46czmvw

w46czmvw1#

你可以像下面这样修改你的序列化器。它从请求上下文中选择用户并创建博客。

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

相关问题