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 >
2012-10-05 18:26:53 +04:00
< link href = "http://tomchristie.github.com/django-rest-framework/img/favicon.ico" rel = "icon" type = "image/x-icon" >
2012-09-02 00:24:33 +04:00
< 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-13 12:40:09 +04:00
< link href = "http://tomchristie.github.com/django-rest-framework/css/default.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-10-01 19:27:59 +04:00
< body onload = "prettyPrint()" class = "3-class-based-views-page" >
2012-09-02 00:24:33 +04:00
2012-10-05 22:27:27 +04:00
< div class = "wrapper" >
2012-09-02 00:24:33 +04:00
< div class = "navbar navbar-inverse navbar-fixed-top" >
< div class = "navbar-inner" >
< div class = "container-fluid" >
2012-09-12 16:12:00 +04:00
< a class = "repo-link btn btn-primary btn-small" href = "https://github.com/tomchristie/django-rest-framework/tree/restframework2" > GitHub< / a >
2012-09-02 00:24:33 +04:00
< 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-10-09 15:01:56 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/tutorial/quickstart" > Quickstart< / a > < / li >
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 >
2012-10-10 12:36:47 +04:00
<!-- <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 >
2012-10-05 20:10:33 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/fields" > Serializer fields< / a > < / li >
2012-09-02 00:37:41 +04:00
< 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-10-01 19:27:59 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/api-guide/pagination" > Pagination< / 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 >
2012-10-13 18:09:05 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/browser-enhancements" > Browser enhancements< / a > < / li >
2012-10-13 18:35:46 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/browsable-api" > The Browsable API< / a > < / li >
2012-10-08 15:19:26 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/rest-hypermedia-hateoas" > REST, Hypermedia & HATEOAS< / 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-10-08 15:19:26 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/migration" > 2.0 Migration Guide< / a > < / li >
2012-10-17 16:50:08 +04:00
< li > < a href = "http://tomchristie.github.com/django-rest-framework/topics/release-notes" > Release Notes< / 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-10-09 17:13:19 +04:00
<!-- TODO
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 >
2012-10-09 17:13:19 +04:00
-->
2012-09-08 11:03:30 +04:00
< / ul >
2012-09-02 00:24:33 +04:00
< / div > <!-- /.nav - collapse -->
< / div >
< / div >
< / div >
2012-10-05 22:27:27 +04:00
< div class = "body-content" >
< div class = "container-fluid" >
< div class = "row-fluid" >
2012-10-05 16:22:18 +04:00
2012-10-05 22:27:27 +04:00
< div class = "span3" >
2012-10-08 15:19:26 +04:00
<!-- TODO
< p style = "margin-top: -12px" >
< a class = "btn btn-mini btn-primary" style = "width: 60px" > « previous< / a >
< a class = "btn btn-mini btn-primary" style = "float: right; margin-right: 8px; width: 60px;" > next » < / a >
< / p >
-->
2012-10-05 22:27:27 +04:00
< div id = "table-of-contents" >
< ul class = "nav nav-list side-nav well sidebar-nav-fixed" >
< 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-10-05 22:27:27 +04:00
< / ul >
< / div >
2012-09-08 11:03:30 +04:00
< / div >
2012-09-02 00:24:33 +04:00
2012-10-05 22:27:27 +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
2012-09-20 16:07:16 +04:00
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework 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-10-05 01:32:43 +04:00
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2012-09-02 00:24:33 +04:00
< / code > < / pre >
2012-10-05 01:32:43 +04:00
< p > So far, so good. It looks pretty similar to the previous case, but we've got better separation 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():
2012-09-25 16:40:44 +04:00
comment = serializer.object
2012-09-02 00:24:33 +04:00
comment.save()
return Response(serializer.data)
2012-09-17 23:21:26 +04:00
return Response(serializer.errors, 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-17 23:21:26 +04:00
< / code > < / pre >
< p > That's looking good. Again, it's still pretty similar to the function based view right now.< / p >
< p > We'll also need to refactor our URLconf slightly now we're using class based views.< / p >
< pre class = "prettyprint lang-py" > < code > from django.conf.urls import patterns, url
2012-09-20 16:07:16 +04:00
from rest_framework.urlpatterns import format_suffix_patterns
2012-09-17 23:21:26 +04:00
from blogpost import views
2012-09-02 00:24:33 +04:00
2012-09-17 23:21:26 +04:00
urlpatterns = patterns('',
url(r'^$', views.CommentRoot.as_view()),
url(r'^(?P< pk> [0-9]+)$', views.CommentInstance.as_view())
)
urlpatterns = format_suffix_patterns(urlpatterns)
2012-09-02 00:24:33 +04:00
< / code > < / pre >
2012-09-17 23:21:26 +04:00
< p > 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-20 16:07:16 +04:00
from rest_framework import mixins
from rest_framework 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
< / 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-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-20 16:07:16 +04:00
from rest_framework import generics
2012-09-02 00:24:33 +04:00
2012-10-05 01:32:43 +04:00
class CommentRoot(generics.ListCreateAPIView):
2012-09-02 00:24:33 +04:00
model = Comment
serializer_class = CommentSerializer
2012-10-05 01:32:43 +04:00
class CommentInstance(generics.RetrieveUpdateDestroyAPIView):
2012-09-02 00:24:33 +04:00
model = Comment
serializer_class = CommentSerializer
< / code > < / pre >
2012-10-05 01:32:43 +04:00
< p > Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic 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-10-05 22:27:27 +04:00
< / div > <!-- /span -->
< / div > <!-- /row -->
< / div > <!-- /.fluid - container -->
< / div > <!-- /.body content -->
2012-09-02 00:24:33 +04:00
2012-10-05 18:26:53 +04:00
< div id = "push" > < / div >
2012-10-05 22:27:27 +04:00
< / div > <!-- /.wrapper -->
2012-10-05 18:26:53 +04:00
2012-10-05 22:27:27 +04:00
< footer class = "span12" >
2012-10-05 22:33:52 +04:00
< p > Sponsored by < a href = "http://dabapps.com/" > DabApps< / a > .< / a > < / p >
2012-10-05 22:27:27 +04:00
< / footer >
2012-10-05 18:26:53 +04:00
2012-09-02 00:24:33 +04:00
<!-- 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-10-05 16:22:18 +04:00
< script src = "http://tomchristie.github.com/django-rest-framework/js/prettify-1.0.js" > < / script >
< script src = "http://tomchristie.github.com/django-rest-framework/js/bootstrap-2.1.1-min.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
2012-09-17 23:21:26 +04:00
$('.dropdown-menu').on('click touchstart', function(event) {
2012-09-12 13:14:01 +04:00
event.stopPropagation();
});
2012-09-02 00:24:33 +04:00
< / script >
2012-10-01 19:27:59 +04:00
< / body > < / html >