django rest框架-POST请求导致400状态代码

时间:2018-12-07 03:46:28

标签: django model-view-controller django-rest-framework serializer django-serializer

我正在尝试执行POST请求以创建文章,并且出现此错误Request failed with status code 400 Bad Request: /api/articles/create/

文章需要创建3个属性:
(1)标题
(2)身体
(3)作者(当前用户)

由于POST请求进入post类的ArticleCreateView方法中,因此路由器工作正常。但是我猜测serializer.is_valid()由于某种原因返回了False。 此外,print(request.data)返回{'title': 'hello', 'body': 'stuff'}

关于Django的另一个奥秘是,序列化程序如何知道我是否要获取,创建或更新某些内容?在我看到的所有示例中,串行器似乎都知道这一点。

class ArticleCreateView(CreateAPIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = ArticleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'

    def create(self, validated_data):
        author = self.context['request'].user
        title = validated_data.get('title')
        body = validated_data.get('body')
        return Article.objects.create(author=author, title=title, body=body)


class Article(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    body = models.TextField(max_length=100)
    date_updated = models.DateTimeField(auto_now=True)
    date_created = models.DateTimeField(auto_now_add=True)

2 个答案:

答案 0 :(得分:1)

添加此

serializer = ArticleSerializer(data=request.data, context={'request':request})

答案 1 :(得分:1)

根据您的序列化程序,验证过程需要 author 详细信息,而这些详细信息不会通过POST有效负载传递。
因此,通过添加 author 或使用 required=False <,将序列化器中的 ReadOnlyField() 字段设为非必填字段/ strong>,或在元类中指定 read_only_fields 。还传递@nishant所述的上下文数据

# views.py
class ArticleCreateView(CreateAPIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = ArticleSerializer(data=request.data, context={"request": request}) # change here 
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)
# serializer.py
class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'
        read_only_fields = ('author',)

    def create(self, validated_data):
        author = self.context['request'].user
        title = validated_data.get('title')
        body = validated_data.get('body')
        return Article.objects.create(author=author, title=title, body=body)