2012-09-02 00:24:33 +04:00
<!DOCTYPE html>
< html lang = "en" > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >
< meta charset = "utf-8" >
< title > Django REST framework< / title >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< meta name = "description" content = "" >
< meta name = "author" content = "" >
<!-- Le styles -->
2012-09-08 23:24:07 +04:00
< link href = "http://tomchristie.github.com/django-rest-framework/css/prettify.css" rel = "stylesheet" >
2012-09-02 00:37:41 +04:00
< link href = "http://tomchristie.github.com/django-rest-framework/css/bootstrap.css" rel = "stylesheet" >
< link href = "http://tomchristie.github.com/django-rest-framework/css/bootstrap-responsive.css" rel = "stylesheet" >
2012-09-08 11:03:30 +04:00
< link href = "http://tomchristie.github.com/django-rest-framework/css/drf-styles.css" rel = "stylesheet" >
2012-09-02 00:24:33 +04:00
<!-- Le HTML5 shim, for IE6 - 8 support of HTML5 elements -->
<!-- [if lt IE 9]>
< script src = "http://html5shim.googlecode.com/svn/trunk/html5.js" > < / script >
<![endif]-->
2012-09-09 19:56:34 +04:00
< body onload = "prettyPrint()" class = "3-class-based-views" >
2012-09-02 00:24:33 +04:00
< div class = "navbar navbar-inverse navbar-fixed-top" >
< div class = "navbar-inner" >
< div class = "container-fluid" >
< a class = "btn btn-navbar" data-toggle = "collapse" data-target = ".nav-collapse" >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< / a >
2012-09-02 00:37:41 +04:00
< a class = "brand" href = "http://tomchristie.github.com/django-rest-framework" > Django REST framework< / a >
2012-09-02 00:24:33 +04:00
< div class = "nav-collapse collapse" >
< ul class = "nav" >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework" > Home< / a > < / li >
2012-09-02 00:24:33 +04:00
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Tutorial < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/1-serialization" > 1 - Serialization< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/2-requests-and-responses" > 2 - Requests and responses< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/3-class-based-views" > 3 - Class based views< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/4-authentication-permissions-and-throttling" > 4 - Authentication, permissions and throttling< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/5-relationships-and-hyperlinked-apis" > 5 - Relationships and hyperlinked APIs< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/6-resource-orientated-projects" > 6 - Resource orientated projects< / a > < / li >
2012-09-02 00:24:33 +04:00
< / ul >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > API Guide < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/requests" > Requests< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/responses" > Responses< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/views" > Views< / a > < / li >
2012-09-12 13:14:01 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/generic-views" > Generic views< / a > < / li >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/parsers" > Parsers< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/renderers" > Renderers< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/serializers" > Serializers< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/authentication" > Authentication< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/permissions" > Permissions< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/throttling" > Throttling< / a > < / li >
2012-09-12 13:14:01 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/content-negotiation" > Content negotiation< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/format-suffixes" > Format suffixes< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/reverse" > Returning URLs< / a > < / li >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/exceptions" > Exceptions< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/status-codes" > Status codes< / a > < / li >
2012-09-05 16:05:36 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/settings" > Settings< / a > < / li >
2012-09-02 00:24:33 +04:00
< / ul >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Topics < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/csrf" > Working with AJAX and CSRF< / a > < / li >
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/formoverloading" > Browser based PUT, PATCH and DELETE< / a > < / li >
2012-09-05 16:05:36 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/contributing" > Contributing to REST framework< / a > < / li >
2012-09-02 00:37:41 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/credits" > Credits< / a > < / li >
2012-09-02 00:24:33 +04:00
< / ul >
< / li >
< / ul >
< ul class = "nav pull-right" >
2012-09-08 11:03:30 +04:00
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Version: 2.0.0 < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li > < a href = "#" > Trunk< / a > < / li >
< li > < a href = "#" > 2.0.0< / a > < / li >
< / ul >
< / li >
< / ul >
2012-09-02 00:24:33 +04:00
< / div > <!-- /.nav - collapse -->
< / div >
< / div >
< / div >
< div class = "container-fluid" >
< div class = "row-fluid" >
2012-09-08 11:03:30 +04:00
< div class = "span3" >
< div id = "table-of-contents" class = "well affix span3" >
< ul class = "nav nav-list side-nav" >
< li class = "main" > < a href = "#tutorial-3-class-based-views" > Tutorial 3: Class Based Views< / a > < / li >
2012-09-02 00:24:33 +04:00
< li > < a href = "#rewriting-our-api-using-class-based-views" > Rewriting our API using class based views< / a > < / li >
< li > < a href = "#using-mixins" > Using mixins< / a > < / li >
2012-09-07 12:45:23 +04:00
< li > < a href = "#using-generic-class-based-views" > Using generic class based views< / a > < / li >
2012-09-02 00:24:33 +04:00
2012-09-08 11:03:30 +04:00
< / ul >
< / div >
2012-09-02 00:24:33 +04:00
< / div >
2012-09-08 11:03:30 +04:00
< div id = "main-content" class = "span9" >
< h1 id = "tutorial-3-class-based-views" > Tutorial 3: Class Based Views< / h1 >
2012-09-02 00:24:33 +04:00
< p > We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code < a href = "http://en.wikipedia.org/wiki/Don't_repeat_yourself" > DRY< / a > .< / p >
< h2 id = "rewriting-our-api-using-class-based-views" > Rewriting our API using class based views< / h2 >
< p > We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from blog.models import Comment
2012-09-08 11:03:30 +04:00
from blog.serializers import CommentSerializer
2012-09-02 00:24:33 +04:00
from django.http import Http404
from djangorestframework.views import APIView
from djangorestframework.response import Response
2012-09-08 11:03:30 +04:00
from djangorestframework import status
2012-09-02 00:24:33 +04:00
2012-09-05 16:05:36 +04:00
class CommentRoot(APIView):
2012-09-02 00:24:33 +04:00
"""
List all comments, or create a new comment.
2012-09-08 11:03:30 +04:00
"""
2012-09-02 00:24:33 +04:00
def get(self, request, format=None):
comments = Comment.objects.all()
2012-09-08 11:03:30 +04:00
serializer = CommentSerializer(instance=comments)
2012-09-02 00:24:33 +04:00
return Response(serializer.data)
2012-09-08 11:03:30 +04:00
def post(self, request, format=None):
serializer = CommentSerializer(request.DATA)
2012-09-02 00:24:33 +04:00
if serializer.is_valid():
comment = serializer.object
comment.save()
2012-09-08 11:03:30 +04:00
return Response(serializer.serialized, status=status.HTTP_201_CREATED)
return Response(serializer.serialized_errors, status=status.HTTP_400_BAD_REQUEST)
2012-09-05 16:05:36 +04:00
2012-09-08 11:03:30 +04:00
comment_root = CommentRoot.as_view()
2012-09-02 00:24:33 +04:00
< / code > < / pre >
< p > So far, so good. It looks pretty similar to the previous case, but we've got better seperation between the different HTTP methods. We'll also need to update the instance view. < / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > class CommentInstance(APIView):
2012-09-02 00:24:33 +04:00
"""
Retrieve, update or delete a comment instance.
"""
def get_object(self, pk):
try:
2012-09-05 16:05:36 +04:00
return Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
2012-09-02 00:24:33 +04:00
raise Http404
def get(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(instance=comment)
return Response(serializer.data)
def put(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(request.DATA, instance=comment)
if serializer.is_valid():
comment = serializer.deserialized
comment.save()
return Response(serializer.data)
2012-09-05 16:05:36 +04:00
return Response(serializer.error_data, status=status.HTTP_400_BAD_REQUEST)
2012-09-02 00:24:33 +04:00
def delete(self, request, pk, format=None):
comment = self.get_object(pk)
comment.delete()
2012-09-05 16:05:36 +04:00
return Response(status=status.HTTP_204_NO_CONTENT)
2012-09-02 00:24:33 +04:00
2012-09-08 11:03:30 +04:00
comment_instance = CommentInstance.as_view()
2012-09-02 00:24:33 +04:00
< / code > < / pre >
2012-09-05 16:05:36 +04:00
< p > That's looking good. Again, it's still pretty similar to the function based view right now.
Okay, we're done. If you run the development server everything should be working just as before.< / p >
2012-09-02 00:24:33 +04:00
< h2 id = "using-mixins" > Using mixins< / h2 >
< p > One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.< / p >
2012-09-07 12:45:23 +04:00
< p > The create/retrieve/update/delete operations that we've been using so far are going to be pretty simliar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.< / p >
< p > Let's take a look at how we can compose our views by using the mixin classes.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from blog.models import Comment
2012-09-02 00:24:33 +04:00
from blog.serializers import CommentSerializer
2012-09-05 16:05:36 +04:00
from djangorestframework import mixins
2012-09-07 12:45:23 +04:00
from djangorestframework import generics
2012-09-02 00:24:33 +04:00
2012-09-05 16:05:36 +04:00
class CommentRoot(mixins.ListModelMixin,
mixins.CreateModelMixin,
2012-09-07 12:45:23 +04:00
generics.MultipleObjectBaseView):
2012-09-02 00:24:33 +04:00
model = Comment
serializer_class = CommentSerializer
2012-09-05 16:05:36 +04:00
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
2012-09-02 00:24:33 +04:00
2012-09-05 16:05:36 +04:00
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
2012-09-07 12:45:23 +04:00
comment_root = CommentRoot.as_view()
< / code > < / pre >
< p > We'll take a moment to examine exactly what's happening here - We're building our view using < code > MultipleObjectBaseView< / code > , and adding in < code > ListModelMixin< / code > and < code > CreateModelMixin< / code > .< / p >
< p > The base class provides the core functionality, and the mixin classes provide the < code > .list()< / code > and < code > .create()< / code > actions. We're then explictly binding the < code > get< / code > and < code > post< / code > methods to the appropriate actions. Simple enough stuff so far.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > class CommentInstance(mixins.RetrieveModelMixin,
2012-09-05 16:05:36 +04:00
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
2012-09-07 12:45:23 +04:00
generics.SingleObjectBaseView):
2012-09-02 00:24:33 +04:00
model = Comment
serializer_class = CommentSerializer
2012-09-05 16:05:36 +04:00
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
2012-09-07 12:45:23 +04:00
comment_instance = CommentInstance.as_view()
2012-09-02 00:24:33 +04:00
< / code > < / pre >
2012-09-07 12:45:23 +04:00
< p > Pretty similar. This time we're using the < code > SingleObjectBaseView< / code > class to provide the core functionality, and adding in mixins to provide the < code > .retrieve()< / code > , < code > .update()< / code > and < code > .destroy()< / code > actions.< / p >
< h2 id = "using-generic-class-based-views" > Using generic class based views< / h2 >
< p > Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use.< / p >
2012-09-08 23:24:07 +04:00
< pre class = "prettyprint lang-py" > < code > from blog.models import Comment
2012-09-02 00:24:33 +04:00
from blog.serializers import CommentSerializer
2012-09-07 12:45:23 +04:00
from djangorestframework import generics
2012-09-02 00:24:33 +04:00
2012-09-07 12:45:23 +04:00
class CommentRoot(generics.RootAPIView):
2012-09-02 00:24:33 +04:00
model = Comment
serializer_class = CommentSerializer
2012-09-07 12:45:23 +04:00
comment_root = CommentRoot.as_view()
class CommentInstance(generics.InstanceAPIView):
2012-09-02 00:24:33 +04:00
model = Comment
serializer_class = CommentSerializer
2012-09-07 12:45:23 +04:00
comment_instance = CommentInstance.as_view()
2012-09-02 00:24:33 +04:00
< / code > < / pre >
2012-09-07 12:45:23 +04:00
< p > Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idomatic Django.< / p >
2012-09-05 21:26:37 +04:00
< p > Next we'll move onto < a href = "4-authentication-permissions-and-throttling" > part 4 of the tutorial< / a > , where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.< / p >
2012-09-02 00:24:33 +04:00
< / div > <!-- /span -->
< / div > <!-- /row -->
< / div > <!-- /.fluid - container -->
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
2012-09-08 11:03:30 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/jquery-1.8.1-min.js" > < / script >
2012-09-08 23:24:07 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/prettify.js" > < / script >
2012-09-02 00:37:41 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-dropdown.js" > < / script >
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-scrollspy.js" > < / script >
2012-09-08 11:03:30 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-collapse.js" > < / script >
2012-09-02 00:24:33 +04:00
< script >
2012-09-08 11:03:30 +04:00
//$('.side-nav').scrollspy()
var shiftWindow = function() { scrollBy(0, -50) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
2012-09-12 13:14:01 +04:00
$('.dropdown-menu').click(function(event) {
event.stopPropagation();
});
2012-09-02 00:24:33 +04:00
< / script >
< / body > < / html >