keyerror in Django REST Framework Serializer.save() and validated_data

Viewed 272

I'm new on Django Rest Framework and when I want to POST data and I get this error KeyError at author=self.validated_data['author'], KeyError: 'author' Here's my code: in my models.py

class Question(models.Model):
#author
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
#question
question=answer=models.TextField(default='Write your question')
#answer
answer=models.TextField(default='write your answer')
#paragraph
paragraph=models.ForeignKey(Paragraph,on_delete=models.CASCADE)
#date
published_date = models.DateTimeField(verbose_name='published_date', auto_now_add=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return "{} - {} - {} - {}".format(self.author, self.question, self.answer,self.paragraph)

and my views.py

def question_view(request):

if request.method == 'POST':
    serializer = ParagraphSerializer(data=request.data)
    data = {}
    if serializer.is_valid():
        post = serializer.save()
        data['author'] = post.author
        data['question'] = post.question
        data['answer'] = post.answer
        data['paragraph'] = post.paragraph
    else:
        data = serializer.errors
    return Response(data)

and at the end my Serializers.py

class ParagraphSerializer(serializers.ModelSerializer):
paragraph=serializers.SlugRelatedField(
    many=True,
    read_only=True,
    slug_field='title'
)
author=serializers.SlugRelatedField(
    slug_field=Account.email, 
    required=False,
    read_only=True
)
class Meta:
    model = Question
    fields = ['author','question', 'answer','paragraph']

def save(self):
    post=Question(
                author=self.validated_data['author'],
                question=self.validated_data['question'],
                answer=self.validated_data['answer'],
                paragraph=self.validated_data['paragraph'])
    post.save()
    return post
0 Answers
Related