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?
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With