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:
- we use NoSQL, is the following line still work?
- testItems = Test.objects.all()
- empty request.data in POST JSON request.
- 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
- Can save() be overrided and do custom implementation? How?