如何在Django rest框架中为创建的模型对象保存当前用户

wb1gzix0  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(102)

我有一个模型用来创建一篇文章,文章有一个与Django用户模型相关联的字段:

from django.db import models
from django.contrib.auth.models import User

class Article(models.Model):
    headline = models.CharField(max_length=150)
    body = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    pub_date = models.DateField(auto_now_add=True)
    pub_time = models.TimeField(auto_now_add=True)
    # fields need to be added
        # location 
        # byline -> line tells who writes the article 
        # conclusion
        # tags

    def __str__(self):
        return self.headline

字符串
我使用Django rest框架视图来创建对象。使用Postman并给出作者ID,我可以创建文章帖子:

@api_view(['POST'])
def create(request):
    if request.method == 'POST':
        serializer = ArticleSerializer(data = request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

    return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)


我需要实现的是唯一的登录用户需要能够创建的文章,当用户创建的文章,作者ID需要在对象创建时自动更新。
下面是我的serializer:

from rest_framework import serializers
from . models import Article

class ArticleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Article
        fields  = '__all__'

3zwtqj6y

3zwtqj6y1#

您可以使用具有IsAuthenticated权限的权限装饰器来仅允许通过身份验证的用户,如下所示:

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create(request):
if request.method == 'POST':
    serializer = ArticleSerializer(data = request.data)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)

字符串
上面的代码将只允许经过身份验证的用户使用该视图,直接从登录用户获取用户id的值,而不需要在body请求中发送它。

from rest_framework import serializer
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ['author']

    def create(self, validated_data):
        # Get the authenticated user from the request
        user = self.context['request'].user

        # Add the authenticated user as the author of the article
        validated_data['author'] = user

        # Create the article with the updated data
        return super().create(validated_data)

相关问题