0

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

2 Answers 2

1

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']

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I didn't realize it could be that thing. Now I know that's something I have to be in consider
1

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']

1 Comment

Thank you and for Bhavya as well to make me watch this. I didn't know it could be this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.