Thursday, February 6, 2020

Problem with serialising POST, PUT request in DRF

Hi Devs,

I am trying to implement a CRUD app(modeling blogs) using Django & DRF. I am using rest_framework.serializers.ModelSerializer for serializing my model. While sending a POST, PUT request the serializer is not saving my data, what am I missing?

terminal
Request data:- {'title': 'title 2', 'body': 'body 2'}
Serialized data:- {'pk': 2, 'title': '', 'body': ''}
[06/Feb/2020 17:19:36] "POST /api/blog/ HTTP/1.1" 201 29
[06/Feb/2020 17:19:44] "GET /api/blog/ HTTP/1.1" 200 168
  
views.py
from blog.models import Blog
from blog.serializers import BlogSerializer
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view(["GET", "POST"])
def blog_collection(request):
"""
API for operations on blogs, handles following operations
1. Fetch(GET) the list of blogs.
2. Create(POST) a new blog entry.
"""
if request.method == "POST":
print(f"Request data:- {request.data}")
if request.data == dict():
return Response(status=status.HTTP_400_BAD_REQUEST)

serializer = BlogSerializer(data=request.data)

if serializer.is_valid():
serializer.save()
print(f"Serialized data:- {serializer.data}")
return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
from blog.models import Blog
from rest_framework import serializers


class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = ("pk", "title", "body")


model.py 
from django.db import models


class Blog(models.Model):
_title = models.CharField("Title", max_length=250)
_body = models.TextField("Body")

@property
def title(self):
return self._title

@title.setter
def title(self, value):
self._title = value

@property
def body(self):
return self._body

@body.setter
def body(self, value):
self._body = value

@staticmethod
def get_blogs():
return Blog.objects.all().order_by("id")

@staticmethod
def get_by_pk(pk):
return Blog.objects.get(pk=pk)

@staticmethod
def get_by_attributes(attributes):
return Blog.objects.get(**attributes)

@staticmethod
def create_blog(data):
obj = Blog.objects.create(**data)
obj.save()
return obj

@staticmethod
def update_blog(pk, data):
Blog.objects.filter(pk=pk).update(**data)

@staticmethod
def delete_blog(pk):
Blog.objects.get(pk=pk).delete()

def __str__(self):
return f"<Title:- {self.title[0:50]}>"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAD%3DM5eQs-%2B-htfmsVk_bxqh9WSiS_PxLQcohsHz6r%2BRW%3DhDz7g%40mail.gmail.com.

No comments:

Post a Comment