NOT NULL constraint failed: DJANGO Rest Framework

Question:

I’m following an udemy tutorial, and all it’s going nice until I try to do a POST to create an article on the database.

When I send a POST to /api/posts

with Multipart form:

title: What is Java?

description: Java

order: 1

I receive the error:

NOT NULL constraint failed: posts_post.order

I can’t find the solution to this specific situation. So I let you the code of my:

models.py:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    order = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)

serializers.py:

from rest_framework.serializers import ModelSerializer
from posts.models import Post

class PostSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = ['title', 'description', 'created_at']

views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from posts.models import Post
from posts.api.serializers import PostSerializer

class PostApiView(APIView):
    def get(self, request):
        serializer = PostSerializer(Post.objects.all(), many=True)
        return Response(status=status.HTTP_200_OK, data=serializer.data)

    def post(self, request):
        print(request.POST)
        serializer = PostSerializer(data=request.POST)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_200_OK, data=serializer.data)

I can do a GET request to my api/posts properly. The real problem is the POST request where I should create a new article/post

Asked By: thestuckboy

||

Answers:

The order field is not included in the serializer. You need to add order in the fields.

class PostSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = ['title', 'description', 'order, 'created_at']

Answered By: Bhavya Peshavaria

You are using input as title, description and order but in your serializer you didn’t mention order field so you need to mention order filed in your serializer

class PostSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = ['title', 'description', 'order, 'created_at']
Answered By: sunil ghimire