Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as csrf_exempt. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet, in the views.py module.
@@ -279,8 +278,7 @@ def snippet_detail(request, pk):
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
- else:
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
snippet.delete()
diff --git a/tutorial/3-class-based-views.html b/tutorial/3-class-based-views.html
index 6a5ca721..c807ad0f 100644
--- a/tutorial/3-class-based-views.html
+++ b/tutorial/3-class-based-views.html
@@ -2,7 +2,7 @@
- Django REST framework - Tutorial 3: Class Based Views
+ Tutorial 3: Class Based Views - Django REST framework
diff --git a/tutorial/4-authentication-and-permissions.html b/tutorial/4-authentication-and-permissions.html
index 6e166c08..dc1e2212 100644
--- a/tutorial/4-authentication-and-permissions.html
+++ b/tutorial/4-authentication-and-permissions.html
@@ -2,7 +2,7 @@
- Django REST framework - Tutorial 4: Authentication & Permissions
+ Tutorial 4: Authentication & Permissions - Django REST framework
@@ -337,10 +337,10 @@ class IsOwnerOrReadOnly(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
- if request.method in permissions.SAFE_METHODS:
+ if request.method in permissions.SAFE_METHODS:
return True
- # Write permissions are only allowed to the owner of the snippet
+ # Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user
Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail class: