0
votes

I get stuck on making a simple RESTful test using django-rest-framework. I am new beginner to this. Please help. Thanks in advance!

version:

django >= 1.9

djangorestframework 3.3.3

python 3.4.3

POST request from terminal

curl -H "Content-Type: application/json" -X POST -d '{"title":"xyz","desc":"xyz"}' http://localhost:3000/api/test/

django's settings.py

INSTALLED_APP = {
   'app',
   'rest_framework',
   #....skip to keep it short
}

# did not set anything

<!-- language-all: lang-python -->
REST_FRAMEWORK = {
}

# models.py

class Test(object):
    def __init__(self, title, desc):
        self.title = title
        self.desc = desc

serializers.py

from rest_framework import serializers

class TestSerializer(serializers.Serializer):
    title = serializers.CharField()
    desc = serializers.CharField(max_length=200)
    class Meta:
        model = Test
        fields = ('title', 'desc')

views.py

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
class TestView(APIView):

    def get(self, request, format=None):        
        # 1. we use NoSQL, is the following line still work?
        # testItems = Test.objects.all()
        serializer = SnippetSerializer(testItems, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        # 2. Unable to get any json string in request object or request.data at all!
        # 3. The entire json seems disappear and get dropped
        serializer = TestSerializer(data=request.data)
        if serializer.is_valid():
            # 4. can save() be overrided and do custom implementation? How?
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

from django.conf.urls import patterns, url

urlpatterns = patterns(
    'app',
    url(r'^api/business/$', app.views.TestView.as_view()),
)

My Questions:

  1. we use NoSQL, is the following line still work?
  2. testItems = Test.objects.all()
  3. empty request.data in POST JSON request.
  4. Unable to get any json string in request object or request.data at all! The entire json seems disappear and get dropped. Tried to use Fiddler/Postman capture and ensure JSON did sent out
  5. Can save() be overrided and do custom implementation? How?
1

1 Answers

1
votes

I don't know about NOSQL but you can test it on shell. I'm guessing probably it works. About request.data error; request.data is only used for file upload with django rest framework. When you post a json, it's in the body of the request. What you should do is something like this in your view:

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
import json

@csrf_exempt
class TestView(APIView):

# your get request here.

    def post(self, request, format=None):
        body_unicode = request.body.decode('utf-8')
        data = json.loads(body_unicode)
        # Now, your json content is stores in data as a dictionary.
        serializer = TestSerializer(data=request.data)
        if serializer.is_valid():
            # 4. can save() be overrided and do custom implementation? How?
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

FYI,I use serializers for just creating json, I don't use it to create object. Therefore, I'm not sure if this version %100 works or not. But I'm pretty sure that 2 line I've added turns JSON to dictionary. If serializer accepts dictionary as a data, it'll work.