Django RestFrameWork中的错误“ NOT NULL约束失败:qoura_question.author_id”

时间:2019-06-02 10:43:15

标签: python django

尝试向DRF添加帖子,该帖子会自动获取USER和TIME的信息,但这是尝试添加帖子时弹出的错误。

models.py:

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

class Post(models.Model):
    title = models.CharField(max_length = 200)
    description = models.CharField(max_length = 2000)
    date_posted = models.DateTimeField(default = timezone.now)
    author = models.ForeignKey(User , on_delete = models.CASCADE)

    def __str__(self):
        return self.title

Views.py:

class PostViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    authentication_classes = [TokenAuthentication,SessionAuthentication]

    def create(self, request):

        obj = Post()
        obj.title = request.data['title']
        obj.description = request.data['description']
        obj.date_posted = request.data['date_posted']
        obj.user = request.user
        obj.save()
        return Response(status=status.HTTP_201_CREATED)

serializer.py:

from rest_framework import serializers
from django.contrib.auth.models import User
from . models import Post

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'title','description','date_posted','author')

0 个答案:

没有答案