Created
August 28, 2012 15:31
-
-
Save tomchristie/3499147 to your computer and use it in GitHub Desktop.
Example of writing views with django-serializers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# serializers.py | |
class CommentSerializer(serializers.Serializer): | |
email = serializers.EmailField() | |
content = serializers.CharField(max_length=200) | |
created = serializers.DateTimeField() | |
def restore_object(self, attrs, instance=None): | |
""" | |
Create or update a new comment instance. | |
""" | |
if instance: | |
instance.email = attrs['email'] | |
instance.content = attrs['content'] | |
instance.created = attrs['created'] | |
return instance | |
return models.Comment(**attrs) | |
# views.py | |
class JSONResponse(HttpResponse): | |
""" | |
An HttpResponse that renders it's content into JSON. | |
""" | |
def __init__(self, data, **kwargs): | |
content = JSONRenderer().render(data) | |
kwargs['content_type'] = 'application/json' | |
super(JSONResponse, self).__init__(content, **kwargs) | |
def comment_root(request): | |
""" | |
List all comments, or create a new comment. | |
""" | |
if request.method == 'GET': | |
comments = Comment.objects.all() | |
serializer = CommentSerializer(instance=comments) | |
return JSONResponse(serializer.data) | |
elif request.method == 'POST': | |
data = JSONParser().parse(request) | |
serializer = CommentSerializer(data) | |
if serializer.is_valid(): | |
comment = serializer.object | |
comment.save() | |
return JSONResponse(serializer.data, status=201) | |
else: | |
return JSONResponse(serializer.error_data, status=400) | |
def comment_instance(request, pk): | |
""" | |
Retrieve, update or delete a comment instance. | |
""" | |
try: | |
comment = Comment.objects.get(pk=pk) | |
except Comment.DoesNotExist: | |
return HttpResponse(status=404) | |
if request.method == 'GET': | |
serializer = CommentSerializer(instance=comment) | |
return JSONResponse(serializer.data) | |
elif request.method == 'PUT': | |
data = JSONParser().parse(request) | |
serializer = CommentSerializer(data, instance=comment) | |
if serializer.is_valid(): | |
comment = serializer.object | |
comment.save() | |
return JSONResponse(serializer.data) | |
else: | |
return JSONResponse(serializer.error_data, status=400) | |
elif request.method == 'DELETE': | |
comment.delete() | |
return HttpResponse(status=204) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment