diff options
| author | James Rutherford | 2015-03-11 10:38:03 +0000 | 
|---|---|---|
| committer | James Rutherford | 2015-03-11 10:38:03 +0000 | 
| commit | 4a2d27975ab5249269aebafd803be87a2107092b (patch) | |
| tree | 55b524c93b02eef404304f734be98871bbb1324f /docs/tutorial/4-authentication-and-permissions.md | |
| parent | 856dc855c952746f566a6a8de263afe951362dfb (diff) | |
| parent | dc56e5a0f41fdd6350e91a5749023d086bd1640f (diff) | |
| download | django-rest-framework-4a2d27975ab5249269aebafd803be87a2107092b.tar.bz2 | |
Merge pull request #1 from tomchristie/master
Merge in from upstream
Diffstat (limited to 'docs/tutorial/4-authentication-and-permissions.md')
| -rw-r--r-- | docs/tutorial/4-authentication-and-permissions.md | 83 | 
1 files changed, 52 insertions, 31 deletions
| diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 393d879a..887d1e56 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -12,7 +12,7 @@ Currently our API doesn't have any restrictions on who can edit or delete code s  We're going to make a couple of changes to our `Snippet` model class.  First, let's add a couple of fields.  One of those fields will be used to represent the user who created the code snippet.  The other field will be used to store the highlighted HTML representation of the code. -Add the following two fields to the model. +Add the following two fields to the `Snippet` model in `models.py`.      owner = models.ForeignKey('auth.User', related_name='snippets')      highlighted = models.TextField() @@ -43,21 +43,23 @@ And now we can add a `.save()` method to our model class:  When that's all done we'll need to update our database tables.  Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again. -    rm tmp.db -    python ./manage.py syncdb +    rm -f tmp.db db.sqlite3 +    rm -r snippets/migrations +    python manage.py makemigrations snippets +    python manage.py migrate  You might also want to create a few different users, to use for testing the API.  The quickest way to do this will be with the `createsuperuser` command. -    python ./manage.py createsuperuser +    python manage.py createsuperuser  ## Adding endpoints for our User models -Now that we've got some users to work with, we'd better add representations of those users to our API.  Creating a new serializer is easy: +Now that we've got some users to work with, we'd better add representations of those users to our API.  Creating a new serializer is easy. In `serializers.py` add:      from django.contrib.auth.models import User      class UserSerializer(serializers.ModelSerializer): -        snippets = serializers.PrimaryKeyRelatedField(many=True) +        snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())          class Meta:              model = User @@ -65,18 +67,25 @@ Now that we've got some users to work with, we'd better add representations of t  Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. -We'll also add a couple of views.  We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views. +We'll also add a couple of views to `views.py`.  We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views. + +    from django.contrib.auth.models import User +      class UserList(generics.ListAPIView):          queryset = User.objects.all()          serializer_class = UserSerializer -     -     + +      class UserDetail(generics.RetrieveAPIView):          queryset = User.objects.all()          serializer_class = UserSerializer -Finally we need to add those views into the API, by referencing them from the URL conf. +Make sure to also import the `UserSerializer` class + +	from snippets.serializers import UserSerializer + +Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `urls.py`.      url(r'^users/$', views.UserList.as_view()),      url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), @@ -85,24 +94,26 @@ Finally we need to add those views into the API, by referencing them from the UR  Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance.  The user isn't sent as part of the serialized representation, but is instead a property of the incoming request. -The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL. +The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL. + +On the `SnippetList` view class, add the following method: -On **both** the `SnippetList` and `SnippetDetail` view classes, add the following method: +    def perform_create(self, serializer): +        serializer.save(owner=self.request.user) -    def pre_save(self, obj): -        obj.owner = self.request.user +The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.  ## Updating our serializer -Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that.  Add the following field to the serializer definition: +Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that.  Add the following field to the serializer definition in `serializers.py`: -    owner = serializers.Field(source='owner.username') +    owner = serializers.ReadOnlyField(source='owner.username')  **Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.  This field is doing something quite interesting.  The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance.  It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language. -The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc...  The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. +The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc...  The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here.  ## Adding required permissions to views @@ -122,7 +133,7 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai  If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets.  In order to do so we'd need to be able to login as a user. -We can add a login view for use with the browsable API, by editing our URLconf once more. +We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file.  Add the following import at the top of the file: @@ -130,10 +141,10 @@ Add the following import at the top of the file:  And, at the end of the file, add a pattern to include the login and logout views for the browsable API. -    urlpatterns += patterns('', +    urlpatterns += [          url(r'^api-auth/', include('rest_framework.urls',                                     namespace='rest_framework')), -    ) +    ]  The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use.  The only restriction is that the included urls must use the `'rest_framework'` namespace. @@ -150,8 +161,8 @@ To do that we're going to need to create a custom permission.  In the snippets app, create a new file, `permissions.py`      from rest_framework import permissions -     -     + +      class IsOwnerOrReadOnly(permissions.BasePermission):          """          Custom permission to only allow owners of an object to edit it. @@ -160,13 +171,13 @@ In the snippets app, create a new file, `permissions.py`          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: +Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class:      permission_classes = (permissions.IsAuthenticatedOrReadOnly,                            IsOwnerOrReadOnly,) @@ -187,15 +198,25 @@ If we're interacting with the API programmatically we need to explicitly provide  If we try to create a snippet without authenticating, we'll get an error: -    curl -i -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" +    http POST http://127.0.0.1:8000/snippets/ code="print 123" -    {"detail": "Authentication credentials were not provided."} +    { +        "detail": "Authentication credentials were not provided." +    }  We can make a successful request by including the username and password of one of the users we created earlier. -    curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 789" -u tom:password -     -    {"id": 5, "owner": "tom", "title": "foo", "code": "print 789", "linenos": false, "language": "python", "style": "friendly"} +    http -a tom:password POST http://127.0.0.1:8000/snippets/ code="print 789" + +    { +        "id": 5, +        "owner": "tom", +        "title": "foo", +        "code": "print 789", +        "linenos": false, +        "language": "python", +        "style": "friendly" +    }  ## Summary | 
