What's new

Django Rest Framework Not Null Constraint


Active member
Staff member
When i try to create a new by post by posting the following Json:

"title": "This is serialzer title",
"content": "This is serialzer content",

I get the following error:

NOT NULL constraint failed: blog_post.views


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

# Create your models here.

class Post(models.Model):
sno = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
views = models.IntegerField()
slug = models.CharField(max_length=100)
timeStamp = models.DateTimeField(default=now)

def __str__(self):
# return self.title + ' by ' + self.author
return self.title + ' by ' + self.author.username

class BlogComment(models.Model):
sno = models.AutoField(primary_key=True)
comment = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
timeStamp = models.DateTimeField(default=now)

def __str__(self):
return self.comment[0:13] + "..." + " by " + self.user.username


def api_create_blog_view(request):
user = User.objects.get(pk=1)
blog_post = Post(author=user)
if request.method == "POST":
serializer = PostSerializer(blog_post, data=request.data)
if serializer.is_valid():
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


from blog.models import Post
from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['title', 'content']

I don't know how to solve this please help me to solve this error.DB has already been cleared. Locations have been created by using the admin interface. I know that the issue is something trivial, but I just can't get it to work.

Continue reading...