David Foie Gras
David Foie Gras

Reputation: 2080

In DRF(django-rest-framework), null value in column "author_id" violates not-null constraint. What should i do?

I made django project through DRF. enter image description here

From that window, i clicked post so then it did not worked.

traceback

#I almost omitted other codes
Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/comments/

Django Version: 1.9.7
Python Version: 3.5.2

Traceback:

Exception Type: IntegrityError at /comments/
Exception Value: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains (2, comment1, 2016-08-03 13:30:59.536186+00, null, null).

serializers.py

class UserSerializer(serializers.HyperlinkedModelSerializer):
    posts = serializers.HyperlinkedRelatedField(many=True, view_name='post-detail', read_only=True)
    comments = serializers.HyperlinkedRelatedField(many=True, view_name='comment-detail', read_only=True)
    class Meta:
        model = User
        fields = ('url','id', 'pk', 'username', 'email', 'comments', 'posts', 'author')

class CommentSerializer(serializers.HyperlinkedModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')
    post = serializers.ReadOnlyField(source='post.title')
    highlight = serializers.HyperlinkedIdentityField(view_name='comment-highlight', format='html')
    class Meta:
        model = Comment
        fields = ('url','id', 'pk', 'post', 'author', 'text','highlight')

models.py

class Comment(models.Model):
    post = models.ForeignKey('blog.Post', related_name='related_comments')
    author = models.ForeignKey(User, related_name='related_commentwriter')
    text = models.TextField(max_length=500)
    created_date = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.text

Additionally, i'm using django rest auth.

Why this error comes? How to solve this?

Thanks for reading.

Upvotes: 4

Views: 2877

Answers (1)

Anna
Anna

Reputation: 553

You could not create Comment instance with null in author field. For fix it you can add author when you create new comment

class CommentSerializer(serializers.HyperlinkedModelSerializer):
...................

def create(self, validated_data):
    validated_data['author'] = self.context['request'].user
    return super(CommentSerializer, self).create(validated_data)

The same with post field.

Upvotes: 2

Related Questions