Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post to django rest framework

I'd like to post to my Django server using post so I can add a todo item. Here is the model:

class Todo(models.Model):
    title = models.CharField(max_length=200);
    text = models.TextField()
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(default=datetime.now, blank = True )
    def __str__(self):
        return self.title

And serializers:

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = ("id", 'title','text', 'completed', 'created_at')

And view:

class TodoList(APIView):
    def get(self,request):
        todo=Todo.objects.all()
        serializer=TodoSerializer(todo,many=True)
        return Response(serializer.data)
    def post(self,request):
        Todo.objects.create(
            title=request.POST.get('title'),
            text=request.POST.get('text'))
        return HttpResponse(status=201)

My post request is

{ "title": "new title",
  "text": "a test text"}

And it told me

IntegrityError at /todos/
(1048, "Column 'title' cannot be null")

As a newbie at Django, I don't understand this error. Any ideas?

like image 481
Shukai Ni Avatar asked Jul 20 '17 04:07

Shukai Ni


People also ask

Is Django GOOD FOR REST API?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.


1 Answers

You need to access request.data instead of request.POST,

def post(self,request):
    serializer = TodoSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
like image 180
zaidfazil Avatar answered Oct 13 '22 22:10

zaidfazil