From eaae8fb2d973769a827214e0606a7e41028d5d34 Mon Sep 17 00:00:00 2001 From: Alex Burgel Date: Mon, 15 Jul 2013 18:35:13 -0400 Subject: Combined link_* and action_* decorators into detail_route and list_route, marked the originals as deprecated. --- docs/tutorial/6-viewsets-and-routers.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index f16add39..f126ba04 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -25,7 +25,7 @@ Here we've used `ReadOnlyModelViewSet` class to automatically provide the defaul Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class. - from rest_framework.decorators import link + from rest_framework.decorators import detail_route class SnippetViewSet(viewsets.ModelViewSet): """ @@ -39,7 +39,7 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) - @link(renderer_classes=[renderers.StaticHTMLRenderer]) + @detail_route(renderer_classes=[renderers.StaticHTMLRenderer]) def highlight(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) @@ -49,9 +49,9 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. -Notice that we've also used the `@link` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style. +Notice that we've also used the `@detail_route` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style. -Custom actions which use the `@link` decorator will respond to `GET` requests. We could have instead used the `@action` decorator if we wanted an action that responded to `POST` requests. +Custom actions which use the `@detail_route` decorator will respond to `GET` requests. We can use the `methods` argument if we wanted an action that responded to `POST` requests. ## Binding ViewSets to URLs explicitly -- cgit v1.2.3 From 4d8d2340be4de905af3488dc721c7b94b1371ef0 Mon Sep 17 00:00:00 2001 From: Veronica Lynn Date: Wed, 7 Aug 2013 14:00:06 -0400 Subject: Fixed typos in a bunch of docs --- docs/tutorial/1-serialization.md | 2 +- docs/tutorial/3-class-based-views.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 2b214d6a..22d29285 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -236,7 +236,7 @@ Edit the `snippet/views.py` file, and add the following. class JSONResponse(HttpResponse): """ - An HttpResponse that renders it's content into JSON. + An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index c1b3d8f2..9fc424fe 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -81,7 +81,7 @@ Okay, we're done. If you run the development server everything should be workin One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour. -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. +The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. Let's take a look at how we can compose our views by using the mixin classes. -- cgit v1.2.3 From 770d496307f1f9d3c8a95a167a506e59302f0de4 Mon Sep 17 00:00:00 2001 From: martync Date: Tue, 13 Aug 2013 09:19:40 +0200 Subject: Small typo --- docs/tutorial/6-viewsets-and-routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index f16add39..8a1a1ae0 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -10,7 +10,7 @@ A `ViewSet` class is only bound to a set of method handlers at the last moment, Let's take our current set of views, and refactor them into view sets. -First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`. We can remove the two views, and replace then with a single class: +First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`. We can remove the two views, and replace them with a single class: from rest_framework import viewsets -- cgit v1.2.3 From 85ab879a85ac4a7a3f6a965ab78839ac16aed912 Mon Sep 17 00:00:00 2001 From: tom-leys Date: Sat, 31 Aug 2013 19:40:53 +1200 Subject: Updated tutorial part 6: 2 examples were missing includes --- docs/tutorial/6-viewsets-and-routers.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 8a1a1ae0..870632f1 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -61,6 +61,7 @@ To see what's going on under the hood let's first explicitly create a set of vie In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views. from snippets.views import SnippetViewSet, UserViewSet + from rest_framework import renderers snippet_list = SnippetViewSet.as_view({ 'get': 'list', @@ -101,6 +102,7 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do Here's our re-wired `urls.py` file. + from django.conf.urls import patterns, url, include from snippets import views from rest_framework.routers import DefaultRouter -- cgit v1.2.3 From 8b245fed14abff62a34e81f4ce8da1c396ba7712 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 2 Sep 2013 09:17:51 +0100 Subject: Add windows virtualenv activate instruction Closes #1075.--- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index f15e75c0..06eec3c4 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -12,7 +12,7 @@ Create a new Django project named `tutorial`, then start a new app called `quick # Create a virtualenv to isolate our package dependencies locally virtualenv env - source env/bin/activate + source env/bin/activate # On Windows use `env\Scripts\activate` # Install Django and Django REST framework into the virtualenv pip install django -- cgit v1.2.3 From 3d8fad04446110db93ed2a13866e91beb9604934 Mon Sep 17 00:00:00 2001 From: Braulio Soncco Date: Wed, 18 Sep 2013 00:33:05 -0500 Subject: Fixing simple typo --- docs/tutorial/2-requests-and-responses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 30966a10..6ff97f37 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -147,7 +147,7 @@ Similarly, we can control the format of the request that we send, using the `Con # POST using form data curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" - {"id": 3, "title": "", "code": "123", "linenos": false, "language": "python", "style": "friendly"} + {"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"} # POST using JSON curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json" -- cgit v1.2.3 From de6e7accef0f144f4bcae9618604d462b1d9d321 Mon Sep 17 00:00:00 2001 From: John Mee Date: Mon, 23 Sep 2013 14:03:09 +1000 Subject: Mindnumbingly trivial single-char typo. --- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 06eec3c4..80bb9abb 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -85,7 +85,7 @@ Right, we'd better write some views then. Open `quickstart/views.py` and get ty queryset = Group.objects.all() serializer_class = GroupSerializer -Rather that write multiple views we're grouping together all the common behavior into classes called `ViewSets`. +Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`. We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise. -- cgit v1.2.3 From 48a38386afb8a8619d2f089ebce364c7a0a845b4 Mon Sep 17 00:00:00 2001 From: dpetzel Date: Sat, 5 Oct 2013 19:29:25 -0400 Subject: **very minor** typo fix --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 22d29285..e1c0009c 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -225,7 +225,7 @@ For the moment we won't use any of REST framework's other features, we'll just w We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into `json`. -Edit the `snippet/views.py` file, and add the following. +Edit the `snippets/views.py` file, and add the following. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt -- cgit v1.2.3 From 864497eebbd39ab3e811c589a44a43176caef1bf Mon Sep 17 00:00:00 2001 From: dpetzel Date: Sat, 5 Oct 2013 23:16:58 -0400 Subject: Be sure to import UserSerializer --- docs/tutorial/4-authentication-and-permissions.md | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 393d879a..510aa243 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -75,6 +75,10 @@ We'll also add a couple of views. We'd like to just use read-only views for the class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer + +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. -- cgit v1.2.3 From e83bc003234418fc6b21b841de216319491bd38d Mon Sep 17 00:00:00 2001 From: Rikki Date: Wed, 16 Oct 2013 03:03:51 +0100 Subject: Added name of file to edit So reader doesn't have to remember, or check through all the files to find where this code fragment was, mention the file name when it is relevant.--- docs/tutorial/2-requests-and-responses.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 6ff97f37..ba9eb723 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -35,7 +35,7 @@ The wrappers also provide behaviour such as returning `405 Method Not Allowed` r Okay, let's go ahead and start using these new components to write a few views. -We don't need our `JSONResponse` class anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly. +We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly. from rest_framework import status from rest_framework.decorators import api_view @@ -64,7 +64,7 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On 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. +Here is the view for an individual snippet (still in `views.py`). @api_view(['GET', 'PUT', 'DELETE']) def snippet_detail(request, pk): -- cgit v1.2.3 From cb123e896ed2dca230088296db9663af5a53252d Mon Sep 17 00:00:00 2001 From: Rikki Date: Wed, 16 Oct 2013 03:08:43 +0100 Subject: Mention name of file to edit To reduce unnecessary cognitive load of the learner, name the file they are putting this code in.--- docs/tutorial/3-class-based-views.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 9fc424fe..67a75d9f 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -4,7 +4,7 @@ We can also write our API views using class based views, rather than function ba ## Rewriting our API using class based views -We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring. +We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring of `views.py`. from snippets.models import Snippet from snippets.serializers import SnippetSerializer @@ -30,7 +30,7 @@ We'll start by rewriting the root view as a class based view. All this involves return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -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. +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 in `views.py`. class SnippetDetail(APIView): """ @@ -62,7 +62,7 @@ So far, so good. It looks pretty similar to the previous case, but we've got be That's looking good. Again, it's still pretty similar to the function based view right now. -We'll also need to refactor our URLconf slightly now we're using class based views. +We'll also need to refactor our `urls.py` slightly now we're using class based views. from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns @@ -83,7 +83,7 @@ One of the big wins of using class based views is that it allows us to easily co The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. -Let's take a look at how we can compose our views by using the mixin classes. +Let's take a look at how we can compose our `views.py` by using the mixin classes. from snippets.models import Snippet from snippets.serializers import SnippetSerializer @@ -126,7 +126,7 @@ Pretty similar. Again we're using the `GenericAPIView` class to provide the cor ## Using generic class based views -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. +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 to trim down `views.py` even more. from snippets.models import Snippet from snippets.serializers import SnippetSerializer -- cgit v1.2.3 From bf6084895263f827a80191fd6ed4eb437b555f9a Mon Sep 17 00:00:00 2001 From: Rikki Date: Wed, 16 Oct 2013 03:21:43 +0100 Subject: Using the filenames where relevant Sometimes it's hard to tell which file the code is intended to go in. Now it spells it out.--- docs/tutorial/4-authentication-and-permissions.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 510aa243..ecf92a7b 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() @@ -52,7 +52,7 @@ You might also want to create a few different users, to use for testing the API. ## 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 @@ -65,7 +65,7 @@ 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. class UserList(generics.ListAPIView): queryset = User.objects.all() @@ -80,7 +80,7 @@ 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. +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[0-9]+)/$', views.UserDetail.as_view()), @@ -98,7 +98,7 @@ On **both** the `SnippetList` and `SnippetDetail` view classes, add the followin ## 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') -- cgit v1.2.3 From 78c8e6de40f89580b9a4cefb6595d52bc1a6afbc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 18 Oct 2013 09:10:54 +0100 Subject: Update 2-requests-and-responses.md --- docs/tutorial/2-requests-and-responses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index ba9eb723..7fa4f3e4 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -64,7 +64,7 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de 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 (still in `views.py`). +Here is the view for an individual snippet, in the `views.py` module. @api_view(['GET', 'PUT', 'DELETE']) def snippet_detail(request, pk): -- cgit v1.2.3 From c3aeb16557f2cbb1c1218b5af7bab646e4958234 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 18 Oct 2013 09:32:04 +0100 Subject: Update 3-class-based-views.md --- docs/tutorial/3-class-based-views.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 67a75d9f..b37bc31b 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -83,7 +83,7 @@ One of the big wins of using class based views is that it allows us to easily co The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. -Let's take a look at how we can compose our `views.py` by using the mixin classes. +Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again. from snippets.models import Snippet from snippets.serializers import SnippetSerializer @@ -126,7 +126,7 @@ Pretty similar. Again we're using the `GenericAPIView` class to provide the cor ## Using generic class based views -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 to trim down `views.py` even more. +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 to trim down our `views.py` module even more. from snippets.models import Snippet from snippets.serializers import SnippetSerializer -- cgit v1.2.3 From 075b8c1037588a590360ab5290b25648367a26c5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 18 Nov 2013 09:29:09 +0000 Subject: Add User import. Refs #599 --- docs/tutorial/4-authentication-and-permissions.md | 3 +++ 1 file changed, 3 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index ecf92a7b..b472322a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -67,6 +67,9 @@ Because `'snippets'` is a *reverse* relationship on the User model, it will not 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 -- cgit v1.2.3 From ca244ad614e2f6fb4fef1dc9987be996d2624303 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 13 Dec 2013 15:30:59 +0000 Subject: Expanded notes in quickstart. Closes #1127. Closes #1128. --- docs/tutorial/quickstart.md | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 80bb9abb..8bf8c7f5 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -89,6 +89,10 @@ Rather than write multiple views we're grouping together all the common behavior We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise. +Notice that our viewset classes here are a little different from those in the [frontpage example][readme-example-api], as they include `queryset` and `serializer_class` attributes, instead of a `model` attribute. + +For trivial cases you can simply set a `model` attribute on the `ViewSet` class and the serializer and queryset will be automatically generated for you. Setting the `queryset` and/or `serializer_class` attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications. + ## URLs Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... @@ -169,6 +173,7 @@ Great, that was easy! If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide]. +[readme-example-api]: ../#example [image]: ../img/quickstart.png [tutorial]: 1-serialization.md [guide]: ../#api-guide -- cgit v1.2.3 From 802648045476f91f1c4b6a9f507cc08625194c2c Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Tue, 17 Dec 2013 10:30:23 +0100 Subject: Use the BytesIO for buffering bytes and import the one from the compat module. --- docs/tutorial/1-serialization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e1c0009c..4d4e7258 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -183,9 +183,9 @@ At this point we've translated the model instance into Python native datatypes. Deserialization is similar. First we parse a stream into Python native datatypes... - import StringIO + from rest_framework.compat import BytesIO - stream = StringIO.StringIO(content) + stream = BytesIO(content) data = JSONParser().parse(stream) ...then we restore those native datatypes into to a fully populated object instance. -- cgit v1.2.3 From 02ae1682b5585581e88bbd996f7cb7fd22b146f7 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 17 Dec 2013 09:45:28 +0000 Subject: Add note on compat import in tutorial --- docs/tutorial/1-serialization.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 4d4e7258..e015a545 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -183,6 +183,8 @@ At this point we've translated the model instance into Python native datatypes. Deserialization is similar. First we parse a stream into Python native datatypes... + # This import will use either `StringIO.StringIO` or `io.BytesIO` + # as appropriate, depending on if we're running Python 2 or Python 3. from rest_framework.compat import BytesIO stream = BytesIO(content) -- cgit v1.2.3 From d6806340e54408858da4b2dc991be99edd65df76 Mon Sep 17 00:00:00 2001 From: amatellanes Date: Mon, 23 Dec 2013 08:50:46 +0100 Subject: Simplified some examples in tutorial --- docs/tutorial/1-serialization.md | 6 ++---- docs/tutorial/2-requests-and-responses.md | 6 ++---- docs/tutorial/4-authentication-and-permissions.md | 7 ++----- 3 files changed, 6 insertions(+), 13 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e015a545..2298df59 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -263,8 +263,7 @@ The root of our API is going to be a view that supports listing all the existing if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) - else: - return JSONResponse(serializer.errors, status=400) + return JSONResponse(serializer.errors, status=400) 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. @@ -290,8 +289,7 @@ We'll also need a view which corresponds to an individual snippet, and can be us if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) - else: - return JSONResponse(serializer.errors, status=400) + return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 7fa4f3e4..603edd08 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -59,8 +59,7 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) - else: - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 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. @@ -85,8 +84,7 @@ Here is the view for an individual snippet, in the `views.py` module. 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/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index b472322a..986f13ff 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -163,15 +163,12 @@ In the snippets app, create a new file, `permissions.py` """ Custom permission to only allow owners of an object to edit it. """ - + 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: - return True - # Write permissions are only allowed to the owner of the snippet - return obj.owner == request.user + return request.method in permissions.SAFE_METHODS or 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: -- cgit v1.2.3 From 74f1cf635536ea99937954a11fa11531a832ebc2 Mon Sep 17 00:00:00 2001 From: amatellanes Date: Mon, 23 Dec 2013 08:56:34 +0100 Subject: Revert "Simplified some examples in tutorial" This reverts commit d6806340e54408858da4b2dc991be99edd65df76. --- docs/tutorial/1-serialization.md | 6 ++++-- docs/tutorial/2-requests-and-responses.md | 6 ++++-- docs/tutorial/4-authentication-and-permissions.md | 7 +++++-- 3 files changed, 13 insertions(+), 6 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 2298df59..e015a545 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -263,7 +263,8 @@ The root of our API is going to be a view that supports listing all the existing if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) - return JSONResponse(serializer.errors, status=400) + else: + return JSONResponse(serializer.errors, status=400) 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. @@ -289,7 +290,8 @@ We'll also need a view which corresponds to an individual snippet, and can be us if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) - return JSONResponse(serializer.errors, status=400) + else: + return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 603edd08..7fa4f3e4 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -59,7 +59,8 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 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. @@ -84,7 +85,8 @@ Here is the view for an individual snippet, in the `views.py` module. if serializer.is_valid(): serializer.save() return Response(serializer.data) - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + else: + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': snippet.delete() diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 986f13ff..b472322a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -163,12 +163,15 @@ In the snippets app, create a new file, `permissions.py` """ Custom permission to only allow owners of an object to edit it. """ - + 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: + return True + # Write permissions are only allowed to the owner of the snippet - return request.method in permissions.SAFE_METHODS or obj.owner == request.user + 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: -- cgit v1.2.3 From 2846ddb5d2ba84b3905d4dc0593afe3a0d4b2749 Mon Sep 17 00:00:00 2001 From: amatellanes Date: Mon, 23 Dec 2013 09:06:03 +0100 Subject: Simplified some examples in tutorial --- docs/tutorial/1-serialization.md | 6 ++---- docs/tutorial/2-requests-and-responses.md | 6 ++---- docs/tutorial/4-authentication-and-permissions.md | 7 ++----- 3 files changed, 6 insertions(+), 13 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e015a545..2298df59 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -263,8 +263,7 @@ The root of our API is going to be a view that supports listing all the existing if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data, status=201) - else: - return JSONResponse(serializer.errors, status=400) + return JSONResponse(serializer.errors, status=400) 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. @@ -290,8 +289,7 @@ We'll also need a view which corresponds to an individual snippet, and can be us if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) - else: - return JSONResponse(serializer.errors, status=400) + return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': snippet.delete() diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 7fa4f3e4..603edd08 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -59,8 +59,7 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) - else: - return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 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. @@ -85,8 +84,7 @@ Here is the view for an individual snippet, in the `views.py` module. 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/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index b472322a..986f13ff 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -163,15 +163,12 @@ In the snippets app, create a new file, `permissions.py` """ Custom permission to only allow owners of an object to edit it. """ - + 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: - return True - # Write permissions are only allowed to the owner of the snippet - return obj.owner == request.user + return request.method in permissions.SAFE_METHODS or 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: -- cgit v1.2.3 From d8a95b4b6d4480089d38808b45a7b47f30e81cdd Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 23 Dec 2013 09:12:34 +0000 Subject: Back out permissions example change in favor of easier to follow example --- docs/tutorial/4-authentication-and-permissions.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 986f13ff..bdc6b579 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -163,12 +163,15 @@ In the snippets app, create a new file, `permissions.py` """ Custom permission to only allow owners of an object to edit it. """ - + 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. - # Write permissions are only allowed to the owner of the snippet - return request.method in permissions.SAFE_METHODS or obj.owner == request.user + if request.method in permissions.SAFE_METHODS: + return True + + # 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: -- cgit v1.2.3 From 9a8082878a08bb87f5e71f245caedc3c9dfd3616 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 14 Jan 2014 17:13:48 +0000 Subject: Use a local virtualenv, not in the users homedir. --- docs/tutorial/1-serialization.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 2298df59..979c4a3e 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -17,9 +17,8 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on. :::bash - mkdir ~/env - virtualenv ~/env/tutorial - source ~/env/tutorial/bin/activate + virtualenv env + source env/bin/activate Now that we're inside a virtualenv environment, we can install our package requirements. -- cgit v1.2.3 From abb240648c971af83c17cb6f77b274533d40c7f3 Mon Sep 17 00:00:00 2001 From: DanSears Date: Fri, 28 Feb 2014 08:40:45 -0800 Subject: clarified which urls.py to edit --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index bdc6b579..432371f3 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -129,7 +129,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: -- cgit v1.2.3 From cdc7d19034170e5d775166763e6df1220e131d35 Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Mon, 5 May 2014 14:41:10 +0200 Subject: Added missing "to" word --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 979c4a3e..dbe693ed 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -104,7 +104,7 @@ Don't forget to sync the database for the first time. ## Creating a Serializer class -The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following. +The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following. from django.forms import widgets from rest_framework import serializers -- cgit v1.2.3 From 05fc974dc961de6d4e11b7baf51f7b3791c06711 Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Mon, 5 May 2014 14:44:54 +0200 Subject: Added missing "the" word --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index dbe693ed..55b19457 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -143,7 +143,7 @@ The first thing we need to get started on our Web API is to provide a way of ser # Create new instance return Snippet(**attrs) -The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. +The first part of the serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Textarea`. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. -- cgit v1.2.3 From 9e3ba939e152c2eb96d3c9b4460a3d4ce76931cd Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Mon, 5 May 2014 20:27:44 +0200 Subject: Removed superfluous "./"s --- docs/tutorial/4-authentication-and-permissions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 432371f3..491df160 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -44,11 +44,11 @@ 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 + python manage.py syncdb 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 -- cgit v1.2.3 From 9dc5e15e5afaf806378bb52ea2134f8dec2af386 Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Tue, 6 May 2014 13:00:41 +0200 Subject: Added missing "the" word --- docs/tutorial/6-viewsets-and-routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 870632f1..0a7c3363 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -21,7 +21,7 @@ First of all let's refactor our `UserList` and `UserDetail` views into a single queryset = User.objects.all() serializer_class = UserSerializer -Here we've used `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. +Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class. -- cgit v1.2.3 From beb7253a961870a37833b7df6d1dfd3e8c1db778 Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Tue, 6 May 2014 15:06:38 +0200 Subject: Removed unnecessary "that" --- docs/tutorial/6-viewsets-and-routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 0a7c3363..dad71601 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -85,7 +85,7 @@ In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view. -Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual. +Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. urlpatterns = format_suffix_patterns(patterns('snippets.views', url(r'^$', 'api_root'), -- cgit v1.2.3 From e033a0b9a0d655666385cd9831c7f1279573b47f Mon Sep 17 00:00:00 2001 From: Sylvain Bellemare Date: Tue, 6 May 2014 15:07:40 +0200 Subject: Replaced singular "is" by plural "are" --- docs/tutorial/6-viewsets-and-routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index dad71601..04b42f2e 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -138,7 +138,7 @@ You can review the final [tutorial code][repo] on GitHub, or try out a live exam ## Onwards and upwards -We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start: +We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start: * Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests. * Join the [REST framework discussion group][group], and help build the community. -- cgit v1.2.3 From 18eab53e892f2f579fd0bb4e1ca3cb47a074accc Mon Sep 17 00:00:00 2001 From: Emmanouil Date: Wed, 9 Jul 2014 15:53:31 +0100 Subject: Updated quick start project set up order --- docs/tutorial/quickstart.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 8bf8c7f5..04792c69 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -6,8 +6,8 @@ We're going to create a simple API to allow admin users to view and edit the use Create a new Django project named `tutorial`, then start a new app called `quickstart`. - # Set up a new project - django-admin.py startproject tutorial + # Create the project directory + mkdir tutorial cd tutorial # Create a virtualenv to isolate our package dependencies locally @@ -18,6 +18,9 @@ Create a new Django project named `tutorial`, then start a new app called `quick pip install django pip install djangorestframework + # Set up a new project + django-admin.py startproject tutorial + # Create a new app python manage.py startapp quickstart -- cgit v1.2.3 From 62d0d4e5d2f203d2c1694af363bce88cc1a5d483 Mon Sep 17 00:00:00 2001 From: nimiq Date: Wed, 6 Aug 2014 12:45:58 +0200 Subject: Fix style for some text --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 2cf44bf9..aef92d08 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -29,7 +29,7 @@ Unlike all our other API endpoints, we don't want to use JSON, but instead just The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance. -Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your snippets.views add: +Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets.views` add: from rest_framework import renderers from rest_framework.response import Response -- cgit v1.2.3 From 14867705e90b2b5f7e84dc7385d4ffba0c82b3e1 Mon Sep 17 00:00:00 2001 From: sshquack Date: Fri, 15 Aug 2014 20:41:21 -0600 Subject: Specify file names using standard format + Explicitly specify module names in the standard format similar to all the other tutorials + Remove the extra quote around module name --- docs/tutorial/4-authentication-and-permissions.md | 2 +- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 491df160..bdbe00ab 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -129,7 +129,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 the URLconf in our project-level urls.py file. +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: diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index aef92d08..deddb13f 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -4,7 +4,7 @@ At the moment relationships within our API are represented by using primary keys ## Creating an endpoint for the root of our API -Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. +Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: from rest_framework import renderers from rest_framework.decorators import api_view @@ -29,7 +29,7 @@ Unlike all our other API endpoints, we don't want to use JSON, but instead just The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance. -Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets.views` add: +Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add: from rest_framework import renderers from rest_framework.response import Response @@ -43,7 +43,7 @@ Instead of using a concrete generic view, we'll use the base class for represent return Response(snippet.highlighted) As usual we need to add the new views that we've created in to our URLconf. -We'll add a url pattern for our new API root: +We'll add a url pattern for our new API root in `snippets/urls.py`: url(r'^$', 'api_root'), @@ -73,7 +73,7 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial * Relationships use `HyperlinkedRelatedField`, instead of `PrimaryKeyRelatedField`. -We can easily re-write our existing serializers to use hyperlinking. +We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add: class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.Field(source='owner.username') @@ -105,7 +105,7 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p * Our user serializer includes a field that refers to `'snippet-detail'`. * Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`. -After adding all those names into our URLconf, our final `'urls.py'` file should look something like this: +After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this: # API endpoints urlpatterns = format_suffix_patterns(patterns('snippets.views', -- cgit v1.2.3 From 867e441ec07fc182569c3dbe6f86fe42aa6b0cbf Mon Sep 17 00:00:00 2001 From: sshquack Date: Fri, 15 Aug 2014 20:45:28 -0600 Subject: Strip trailing spaces in tutorial --- docs/tutorial/1-serialization.md | 20 ++++++------ docs/tutorial/2-requests-and-responses.md | 8 ++--- docs/tutorial/3-class-based-views.md | 4 +-- docs/tutorial/4-authentication-and-permissions.md | 12 +++---- .../5-relationships-and-hyperlinked-apis.md | 16 ++++----- docs/tutorial/quickstart.md | 38 +++++++++++----------- 6 files changed, 49 insertions(+), 49 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 55b19457..96214f5b 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -81,8 +81,8 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) - - + + class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') @@ -94,7 +94,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) - + class Meta: ordering = ('created',) @@ -122,12 +122,12 @@ The first thing we need to get started on our Web API is to provide a way of ser default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') - + def restore_object(self, attrs, instance=None): """ Create or update a new snippet instance, given a dictionary of deserialized field values. - + Note that if we don't define this method, then deserializing data will simply return a dictionary of items. """ @@ -180,7 +180,7 @@ At this point we've translated the model instance into Python native datatypes. content # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}' -Deserialization is similar. First we parse a stream into Python native datatypes... +Deserialization is similar. First we parse a stream into Python native datatypes... # This import will use either `StringIO.StringIO` or `io.BytesIO` # as appropriate, depending on if we're running Python 2 or Python 3. @@ -196,7 +196,7 @@ Deserialization is similar. First we parse a stream into Python native datatype # True serializer.object # - + Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer. We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments. @@ -264,7 +264,7 @@ The root of our API is going to be a view that supports listing all the existing return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.errors, status=400) -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. +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. @@ -277,11 +277,11 @@ We'll also need a view which corresponds to an individual snippet, and can be us snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) - + if request.method == 'GET': serializer = SnippetSerializer(snippet) return JSONResponse(serializer.data) - + elif request.method == 'PUT': data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 603edd08..e70bbbfc 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -33,7 +33,7 @@ The wrappers also provide behaviour such as returning `405 Method Not Allowed` r ## Pulling it all together -Okay, let's go ahead and start using these new components to write a few views. +Okay, let's go ahead and start using these new components to write a few views. We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly. @@ -69,7 +69,7 @@ Here is the view for an individual snippet, in the `views.py` module. def snippet_detail(request, pk): """ Retrieve, update or delete a snippet instance. - """ + """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: @@ -115,7 +115,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter url(r'^snippets/$', 'snippet_list'), url(r'^snippets/(?P[0-9]+)$', 'snippet_detail'), ) - + urlpatterns = format_suffix_patterns(urlpatterns) We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format. @@ -146,7 +146,7 @@ Similarly, we can control the format of the request that we send, using the `Con curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" {"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"} - + # POST using JSON curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json" diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index b37bc31b..e04072ca 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -30,7 +30,7 @@ We'll start by rewriting the root view as a class based view. All this involves return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -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 in `views.py`. +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 in `views.py`. class SnippetDetail(APIView): """ @@ -72,7 +72,7 @@ We'll also need to refactor our `urls.py` slightly now we're using class based v url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()), ) - + urlpatterns = format_suffix_patterns(urlpatterns) Okay, we're done. If you run the development server everything should be working just as before. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index bdbe00ab..74ad9a55 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -73,12 +73,12 @@ We'll also add a couple of views to `views.py`. We'd like to just use read-only class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer - - + + class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer - + Make sure to also import the `UserSerializer` class from snippets.serializers import UserSerializer @@ -157,8 +157,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. @@ -201,7 +201,7 @@ If we try to create a snippet without authenticating, we'll get an error: 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"} ## Summary diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index deddb13f..9c61fe3d 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -1,6 +1,6 @@ # Tutorial 5: Relationships & Hyperlinked APIs -At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships. +At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships. ## Creating an endpoint for the root of our API @@ -37,7 +37,7 @@ Instead of using a concrete generic view, we'll use the base class for represent class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = (renderers.StaticHTMLRenderer,) - + def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) @@ -78,16 +78,16 @@ We can easily re-write our existing serializers to use hyperlinking. In your `sn class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.Field(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') - + class Meta: model = Snippet fields = ('url', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style') - - + + class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail') - + class Meta: model = User fields = ('url', 'username', 'snippets') @@ -126,9 +126,9 @@ After adding all those names into our URLconf, our final `snippets/urls.py` file views.UserDetail.as_view(), name='user-detail') )) - + # Login and logout views for the browsable API - urlpatterns += patterns('', + urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ) diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 8bf8c7f5..029b56a2 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -46,14 +46,14 @@ First up we're going to define some serializers in `quickstart/serializers.py` t from django.contrib.auth.models import User, Group from rest_framework import serializers - - + + class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') - - + + class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group @@ -68,16 +68,16 @@ Right, we'd better write some views then. Open `quickstart/views.py` and get ty from django.contrib.auth.models import User, Group from rest_framework import viewsets from quickstart.serializers import UserSerializer, GroupSerializer - - + + class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all() serializer_class = UserSerializer - - + + class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. @@ -144,22 +144,22 @@ We're now ready to test the API we've built. Let's fire up the server from the We can now access our API, both from the command-line, using tools like `curl`... - bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ + bash: curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ { - "count": 2, - "next": null, - "previous": null, + "count": 2, + "next": null, + "previous": null, "results": [ { - "email": "admin@example.com", - "groups": [], - "url": "http://127.0.0.1:8000/users/1/", + "email": "admin@example.com", + "groups": [], + "url": "http://127.0.0.1:8000/users/1/", "username": "admin" - }, + }, { - "email": "tom@example.com", - "groups": [ ], - "url": "http://127.0.0.1:8000/users/2/", + "email": "tom@example.com", + "groups": [ ], + "url": "http://127.0.0.1:8000/users/2/", "username": "tom" } ] -- cgit v1.2.3 From 61a1eaa4856dca3879010465fd0d60244450960e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 18 Aug 2014 11:55:22 +0100 Subject: tabs -> spaces --- docs/tutorial/quickstart.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 0e60fa7c..98e5f439 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -6,8 +6,8 @@ We're going to create a simple API to allow admin users to view and edit the use Create a new Django project named `tutorial`, then start a new app called `quickstart`. - # Create the project directory - mkdir tutorial + # Create the project directory + mkdir tutorial cd tutorial # Create a virtualenv to isolate our package dependencies locally -- cgit v1.2.3 From 9372cc8c31fc5d7b3fb3b155ed88b0b6d3c00049 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 20 Aug 2014 16:24:52 +0100 Subject: Deprecate .model attribute on views --- docs/tutorial/quickstart.md | 43 +++++++++++++++++-------------------------- 1 file changed, 17 insertions(+), 26 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 98e5f439..813e9872 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -18,34 +18,23 @@ Create a new Django project named `tutorial`, then start a new app called `quick pip install django pip install djangorestframework - # Set up a new project - django-admin.py startproject tutorial - - # Create a new app - python manage.py startapp quickstart - -Next you'll need to get a database set up and synced. If you just want to use SQLite for now, then you'll want to edit your `tutorial/settings.py` module to include something like this: - - DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': 'database.sql', - 'USER': '', - 'PASSWORD': '', - 'HOST': '', - 'PORT': '' - } - } + # Set up a new project with a single application + django-admin.py startproject tutorial . + cd tutorial + django-admin.py startapp quickstart + cd .. -The run `syncdb` like so: +Now sync your database for the first time: python manage.py syncdb +Make sure to create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example. + Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding... ## Serializers -First up we're going to define some serializers in `quickstart/serializers.py` that we'll use for our data representations. +First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations. from django.contrib.auth.models import User, Group from rest_framework import serializers @@ -66,11 +55,11 @@ Notice that we're using hyperlinked relations in this case, with `HyperlinkedMod ## Views -Right, we'd better write some views then. Open `quickstart/views.py` and get typing. +Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing. from django.contrib.auth.models import User, Group from rest_framework import viewsets - from quickstart.serializers import UserSerializer, GroupSerializer + from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): @@ -100,9 +89,9 @@ For trivial cases you can simply set a `model` attribute on the `ViewSet` class Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... - from django.conf.urls import patterns, url, include + from django.conf.urls import url, include from rest_framework import routers - from quickstart import views + from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) @@ -110,10 +99,10 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. - urlpatterns = patterns('', + urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) - ) + ] Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. @@ -172,6 +161,8 @@ Or directly through the browser... ![Quick start image][image] +If you're working through the browser, make sure to login using the control in the top right corner. + Great, that was easy! If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide]. -- cgit v1.2.3 From da385c9c1f9deeeefd705154a6e6612d6d62f41b Mon Sep 17 00:00:00 2001 From: Collin Anderson Date: Tue, 23 Sep 2014 17:08:38 -0400 Subject: remove patterns and strings from urls #1898 --- docs/tutorial/1-serialization.md | 13 +++++++------ docs/tutorial/2-requests-and-responses.md | 9 +++++---- docs/tutorial/3-class-based-views.md | 4 ++-- docs/tutorial/4-authentication-and-permissions.md | 4 ++-- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 10 +++++----- docs/tutorial/6-viewsets-and-routers.md | 12 ++++++------ 6 files changed, 27 insertions(+), 25 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 96214f5b..b0565d91 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -64,9 +64,9 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. - urlpatterns = patterns('', + urlpatterns = [ url(r'^', include('snippets.urls')), - ) + ] Okay, we're ready to roll. @@ -297,11 +297,12 @@ We'll also need a view which corresponds to an individual snippet, and can be us Finally we need to wire these views up. Create the `snippets/urls.py` file: from django.conf.urls import patterns, url + from snippets import views - urlpatterns = patterns('snippets.views', - url(r'^snippets/$', 'snippet_list'), - url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail'), - ) + urlpatterns = [ + url(r'^snippets/$', views.snippet_list), + url(r'^snippets/(?P[0-9]+)/$', views.snippet_detail), + ] It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index e70bbbfc..136b0135 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -110,11 +110,12 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns + from snippets import views - urlpatterns = patterns('snippets.views', - url(r'^snippets/$', 'snippet_list'), - url(r'^snippets/(?P[0-9]+)$', 'snippet_detail'), - ) + urlpatterns = [ + url(r'^snippets/$', views.snippet_list), + url(r'^snippets/(?P[0-9]+)$', views.snippet_detail), + ] urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index e04072ca..382f078a 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -68,10 +68,10 @@ We'll also need to refactor our `urls.py` slightly now we're using class based v from rest_framework.urlpatterns import format_suffix_patterns from snippets import views - urlpatterns = patterns('', + urlpatterns = [ url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()), - ) + ] urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 74ad9a55..9120e254 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -137,10 +137,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. diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 9c61fe3d..36473ce9 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -108,8 +108,8 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this: # API endpoints - urlpatterns = format_suffix_patterns(patterns('snippets.views', - url(r'^$', 'api_root'), + urlpatterns = format_suffix_patterns([ + url(r'^$', views.api_root), url(r'^snippets/$', views.SnippetList.as_view(), name='snippet-list'), @@ -125,13 +125,13 @@ After adding all those names into our URLconf, our final `snippets/urls.py` file url(r'^users/(?P[0-9]+)/$', views.UserDetail.as_view(), name='user-detail') - )) + ]) # Login and logout views for the browsable API - urlpatterns += patterns('', + urlpatterns += [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), - ) + ] ## Adding pagination diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index b2019520..cf37a260 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -87,14 +87,14 @@ Notice how we're creating multiple views from each `ViewSet` class, by binding t Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. - urlpatterns = format_suffix_patterns(patterns('snippets.views', - url(r'^$', 'api_root'), + urlpatterns = format_suffix_patterns([ + url(r'^$', api_root), url(r'^snippets/$', snippet_list, name='snippet-list'), url(r'^snippets/(?P[0-9]+)/$', snippet_detail, name='snippet-detail'), url(r'^snippets/(?P[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'), url(r'^users/$', user_list, name='user-list'), url(r'^users/(?P[0-9]+)/$', user_detail, name='user-detail') - )) + ]) ## Using Routers @@ -102,7 +102,7 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do Here's our re-wired `urls.py` file. - from django.conf.urls import patterns, url, include + from django.conf.urls import url, include from snippets import views from rest_framework.routers import DefaultRouter @@ -113,10 +113,10 @@ Here's our re-wired `urls.py` file. # The API URLs are now determined automatically by the router. # Additionally, we include the login URLs for the browseable API. - urlpatterns = patterns('', + urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) - ) + ] Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself. -- cgit v1.2.3 From a58cfe167d837d34994b50f52098c552f6b0860e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 9 Oct 2014 09:38:03 +0100 Subject: Update tutorial for 3.0 --- docs/tutorial/1-serialization.md | 79 ++++++++++++----------- docs/tutorial/4-authentication-and-permissions.md | 14 ++-- 2 files changed, 50 insertions(+), 43 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index b0565d91..db5b9ea7 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -41,20 +41,7 @@ Once that's done we can create an app that we'll use to create a simple Web API. python manage.py startapp snippets -The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`. - - DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': 'tmp.db', - 'USER': '', - 'PASSWORD': '', - 'HOST': '', - 'PORT': '', - } - } - -We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. +We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file: INSTALLED_APPS = ( ... @@ -72,7 +59,7 @@ Okay, we're ready to roll. ## Creating a model to work with -For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. +For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. from django.db import models from pygments.lexers import get_all_lexers @@ -98,9 +85,10 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni class Meta: ordering = ('created',) -Don't forget to sync the database for the first time. +We'll also need to create an initial migration for our snippet model, and sync the database for the first time. - python manage.py syncdb + python manage.py makemigrations snippets + python manage.py migrate ## Creating a Serializer class @@ -112,40 +100,39 @@ The first thing we need to get started on our Web API is to provide a way of ser class SnippetSerializer(serializers.Serializer): - pk = serializers.Field() # Note: `Field` is an untyped read-only field. + pk = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, max_length=100) - code = serializers.CharField(widget=widgets.Textarea, - max_length=100000) + code = serializers.CharField(style={'type': 'textarea'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') - def restore_object(self, attrs, instance=None): + def create(self, validated_attrs): """ - Create or update a new snippet instance, given a dictionary - of deserialized field values. + Create and return a new `Snippet` instance, given the validated data. + """ + return Snippet.objects.create(**validated_attrs) - Note that if we don't define this method, then deserializing - data will simply return a dictionary of items. + def update(self, instance, validated_attrs): + """ + Update and return an existing `Snippet` instance, given the validated data. """ - if instance: - # Update existing instance - instance.title = attrs.get('title', instance.title) - instance.code = attrs.get('code', instance.code) - instance.linenos = attrs.get('linenos', instance.linenos) - instance.language = attrs.get('language', instance.language) - instance.style = attrs.get('style', instance.style) - return instance + instance.title = validated_attrs.get('title', instance.title) + instance.code = validated_attrs.get('code', instance.code) + instance.linenos = validated_attrs.get('linenos', instance.linenos) + instance.language = validated_attrs.get('language', instance.language) + instance.style = validated_attrs.get('style', instance.style) + instance.save() + return instance - # Create new instance - return Snippet(**attrs) +The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()` -The first part of the serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. +A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`. -Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Textarea`. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. +The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `style={'type': 'textarea'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. @@ -219,6 +206,24 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') +Once nice property that serializers have is that you can inspect all the fields an serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following: + + >>> from snippets.serializers import SnippetSerializer + >>> serializer = SnippetSerializer() + >>> print repr(serializer) # In python 3 use `print(repr(serializer))` + SnippetSerializer(): + id = IntegerField(label='ID', read_only=True) + title = CharField(allow_blank=True, max_length=100, required=False) + code = CharField(style={'type': 'textarea'}) + linenos = BooleanField(required=False) + language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... + style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... + +It's important to remember that `ModelSerializer` classes don't do anything particularly magically, they are simply a shortcut to creating a serializer class with: + +* An automatically determined set of fields. +* Simple default implementations for the `create()` and `update()` methods. + ## Writing regular Django views using our Serializer Let's see how we can write some API views using our new Serializer class. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 9120e254..adab1b55 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -92,24 +92,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 **both** the `SnippetList` and `SnippetDetail` view classes, add the following method: +On the `SnippetList` view class, add the following method: - def pre_save(self, obj): - obj.owner = self.request.user + def perform_create(self, serializer): + serializer.save(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 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 -- cgit v1.2.3 From 5d247a65c89594a7ab5ce2333612f23eadc6828d Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 9 Oct 2014 15:11:19 +0100 Subject: First pass on nested serializers in HTML --- docs/tutorial/quickstart.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 813e9872..c2dc4bea 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -26,11 +26,13 @@ Create a new Django project named `tutorial`, then start a new app called `quick Now sync your database for the first time: - python manage.py syncdb + python manage.py migrate -Make sure to create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example. +We'll also create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example. -Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding... + python manage.py createsuperuser + +Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding... ## Serializers -- cgit v1.2.3 From 928cbc640ef1db2c3fb96d352f69b8ffb66313e6 Mon Sep 17 00:00:00 2001 From: Raony Guimarães Date: Wed, 19 Nov 2014 13:53:36 -0200 Subject: small type --- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index c2dc4bea..1c398c1f 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -19,7 +19,7 @@ Create a new Django project named `tutorial`, then start a new app called `quick pip install djangorestframework # Set up a new project with a single application - django-admin.py startproject tutorial . + django-admin.py startproject tutorial cd tutorial django-admin.py startapp quickstart cd .. -- cgit v1.2.3 From 04d2635b24f0699ed8ed24436a58c203ad6a9a11 Mon Sep 17 00:00:00 2001 From: Gil Gonçalves Date: Thu, 20 Nov 2014 11:33:42 +0000 Subject: Removed unused import from code snippet in tutorial --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 1 - 1 file changed, 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 36473ce9..50552616 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -6,7 +6,6 @@ At the moment relationships within our API are represented by using primary keys Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: - from rest_framework import renderers from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse -- cgit v1.2.3 From 790a651893c4bc6e68bc4d724d5df4ea3f883ced Mon Sep 17 00:00:00 2001 From: Gil Gonçalves Date: Mon, 24 Nov 2014 08:51:08 +0000 Subject: Fixed database update instructions --- docs/tutorial/4-authentication-and-permissions.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index adab1b55..4e4edeea 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -44,7 +44,9 @@ 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 -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. -- cgit v1.2.3 From 918b9cc6a605ee4701d77f73e93a62f04c2345b0 Mon Sep 17 00:00:00 2001 From: Gil Gonçalves Date: Mon, 24 Nov 2014 08:54:07 +0000 Subject: Added missing import in tutorial snippet --- docs/tutorial/6-viewsets-and-routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index cf37a260..3fad509a 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -60,7 +60,7 @@ To see what's going on under the hood let's first explicitly create a set of vie In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views. - from snippets.views import SnippetViewSet, UserViewSet + from snippets.views import SnippetViewSet, UserViewSet, api_root from rest_framework import renderers snippet_list = SnippetViewSet.as_view({ -- cgit v1.2.3 From 2e726e22a394347b7337eb38a2a3a1b0ccde88bc Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 25 Nov 2014 11:42:43 +0000 Subject: request.DATA, request.FILES -> request.data --- docs/tutorial/2-requests-and-responses.md | 12 ++++++------ docs/tutorial/3-class-based-views.md | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 136b0135..f377c712 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -5,10 +5,10 @@ Let's introduce a couple of essential building blocks. ## Request objects -REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.DATA` attribute, which is similar to `request.POST`, but more useful for working with Web APIs. +REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs. request.POST # Only handles form data. Only works for 'POST' method. - request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. + request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. ## Response objects @@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views. These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed. -The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input. +The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.data` with malformed input. ## Pulling it all together @@ -55,7 +55,7 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de return Response(serializer.data) elif request.method == 'POST': - serializer = SnippetSerializer(data=request.DATA) + serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) @@ -80,7 +80,7 @@ Here is the view for an individual snippet, in the `views.py` module. return Response(serializer.data) elif request.method == 'PUT': - serializer = SnippetSerializer(snippet, data=request.DATA) + serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @@ -92,7 +92,7 @@ Here is the view for an individual snippet, in the `views.py` module. This should all feel very familiar - it is not a lot different from working with regular Django views. -Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.DATA` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. +Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. ## Adding optional format suffixes to our URLs diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 382f078a..0a9ea3f1 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -24,7 +24,7 @@ We'll start by rewriting the root view as a class based view. All this involves return Response(serializer.data) def post(self, request, format=None): - serializer = SnippetSerializer(data=request.DATA) + serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) @@ -49,7 +49,7 @@ So far, so good. It looks pretty similar to the previous case, but we've got be def put(self, request, pk, format=None): snippet = self.get_object(pk) - serializer = SnippetSerializer(snippet, data=request.DATA) + serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) -- cgit v1.2.3 From 200e0b17daecd07de6d1f9926a430d29b3ee948f Mon Sep 17 00:00:00 2001 From: José Padilla Date: Fri, 31 Oct 2014 13:03:39 -0400 Subject: Clean up extra white space --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index db5b9ea7..f9027b68 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -134,7 +134,7 @@ A serializer class is very similar to a Django `Form` class, and includes simila The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `style={'type': 'textarea'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. -We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. +We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. ## Working with Serializers -- cgit v1.2.3 From 34bd2b782875f93471c346230579cc75e52fb2c9 Mon Sep 17 00:00:00 2001 From: Will Stott Date: Wed, 26 Nov 2014 15:48:08 +0000 Subject: a few typos --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index f9027b68..84ed247a 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -206,7 +206,7 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') -Once nice property that serializers have is that you can inspect all the fields an serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following: +One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following: >>> from snippets.serializers import SnippetSerializer >>> serializer = SnippetSerializer() -- cgit v1.2.3 From d0e245baba63dd8e2c0a497fc4f65b34b3d25a4a Mon Sep 17 00:00:00 2001 From: Will Stott Date: Wed, 26 Nov 2014 15:51:28 +0000 Subject: grammar --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 84ed247a..a3c19858 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -219,7 +219,7 @@ One nice property that serializers have is that you can inspect all the fields i language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... -It's important to remember that `ModelSerializer` classes don't do anything particularly magically, they are simply a shortcut to creating a serializer class with: +It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes: * An automatically determined set of fields. * Simple default implementations for the `create()` and `update()` methods. -- cgit v1.2.3 From 731c8421afe3093a78cdabb9c3cc28fa52cd1c8e Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sat, 29 Nov 2014 14:43:05 -0400 Subject: Remove YAML support from core --- docs/tutorial/2-requests-and-responses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index f377c712..06a684b1 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -92,7 +92,7 @@ Here is the view for an individual snippet, in the `views.py` module. This should all feel very familiar - it is not a lot different from working with regular Django views. -Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. +Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. ## Adding optional format suffixes to our URLs -- cgit v1.2.3 From e2ea98e8ab3192fa8d252d33cc03929fcf6ed02f Mon Sep 17 00:00:00 2001 From: Tymur Maryokhin Date: Sat, 29 Nov 2014 20:23:55 +0100 Subject: Fixed typos --- docs/tutorial/6-viewsets-and-routers.md | 4 ++-- docs/tutorial/quickstart.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 3fad509a..816e9da6 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -112,7 +112,7 @@ Here's our re-wired `urls.py` file. router.register(r'users', views.UserViewSet) # The API URLs are now determined automatically by the router. - # Additionally, we include the login URLs for the browseable API. + # Additionally, we include the login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) @@ -130,7 +130,7 @@ That doesn't mean it's always the right approach to take. There's a similar set ## Reviewing our work -With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats. +With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, and comes complete with authentication, per-object permissions, and multiple renderer formats. We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views. diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 1c398c1f..3e1ce0a9 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -100,7 +100,7 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... router.register(r'groups', views.GroupViewSet) # Wire up our API using automatic URL routing. - # Additionally, we include login URLs for the browseable API. + # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) -- cgit v1.2.3 From 34b5db62e560e73516fb569eaf9b71ea5562958f Mon Sep 17 00:00:00 2001 From: phalt Date: Mon, 1 Dec 2014 13:39:53 +0000 Subject: Use httpie for tutorials --- docs/tutorial/1-serialization.md | 48 +++++++++++++++++--- docs/tutorial/2-requests-and-responses.md | 55 ++++++++++++++++++----- docs/tutorial/4-authentication-and-permissions.md | 20 ++++++--- docs/tutorial/quickstart.md | 29 ++++++++++++ 4 files changed, 129 insertions(+), 23 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index a3c19858..3ef65116 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -332,17 +332,51 @@ Quit out of the shell... In another terminal window, we can test the server. -We can get a list of all of the snippets. +We could use `curl`, but let's use a nicer tool called [httpie][httpie] to test our server. It has much nicer formatting and makes our output easier to read. This is especially useful when testing. - curl http://127.0.0.1:8000/snippets/ +You can install httpie on all operating systems using pip: - [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] + pip install httpie -Or we can get a particular snippet by referencing its id. +It can also be installed through [Homebrew][brew] on Mac: - curl http://127.0.0.1:8000/snippets/2/ + brew install httpie - {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"} +Finally, we can get a list of all of the snippets: + + http http://127.0.0.1:8000/snippets/ --body + + [ + { + "id": 1, + "title": "", + "code": "foo = \"bar\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + }, + { + "id": 2, + "title": "", + "code": "print \"hello, world\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + } + ] + +Or we can get a particular snippet by referencing its id: + + http http://127.0.0.1:8000/snippets/2/ --body + + { + "id": 2, + "title": "", + "code": "print \"hello, world\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + } Similarly, you can have the same json displayed by visiting these URLs in a web browser. @@ -359,3 +393,5 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. [sandbox]: http://restframework.herokuapp.com/ [virtualenv]: http://www.virtualenv.org/en/latest/index.html [tut-2]: 2-requests-and-responses.md +[httpie]: https://github.com/jakubroztocil/httpie#installation +[brew]: http://brew.sh diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index f377c712..dcaf7c0c 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -127,31 +127,62 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][ We can get a list of all of the snippets, as before. - curl http://127.0.0.1:8000/snippets/ - - [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] + http http://127.0.0.1:8000/snippets/ --body + + [ + { + "id": 1, + "title": "", + "code": "foo = \"bar\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + }, + { + "id": 2, + "title": "", + "code": "print \"hello, world\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + } + ] We can control the format of the response that we get back, either by using the `Accept` header: - curl http://127.0.0.1:8000/snippets/ -H 'Accept: application/json' # Request JSON - curl http://127.0.0.1:8000/snippets/ -H 'Accept: text/html' # Request HTML + http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON + http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML Or by appending a format suffix: - curl http://127.0.0.1:8000/snippets/.json # JSON suffix - curl http://127.0.0.1:8000/snippets/.api # Browsable API suffix + http http://127.0.0.1:8000/snippets/.json # JSON suffix + http http://127.0.0.1:8000/snippets/.api # Browsable API suffix Similarly, we can control the format of the request that we send, using the `Content-Type` header. # POST using form data - curl -X POST http://127.0.0.1:8000/snippets/ -d "code=print 123" + http --form POST http://127.0.0.1:8000/snippets/ code="print 123" - {"id": 3, "title": "", "code": "print 123", "linenos": false, "language": "python", "style": "friendly"} + { + "id": 3, + "title": "", + "code": "print 123", + "linenos": false, + "language": "python", + "style": "friendly" + } # POST using JSON - curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Content-Type: application/json" - - {"id": 4, "title": "", "code": "print 456", "linenos": true, "language": "python", "style": "friendly"} + http --json POST http://127.0.0.1:8000/snippets/ code="print 456" + + { + "id": 4, + "title": "", + "code": "print 456", + "linenos": true, + "language": "python", + "style": "friendly" + } Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 4e4edeea..15d93a62 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -198,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 POST -a tom:password 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 diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 1c398c1f..41e864cc 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -24,6 +24,10 @@ Create a new Django project named `tutorial`, then start a new app called `quick django-admin.py startapp quickstart cd .. +Optionally, install [httpie][httpie] for tastier HTTP requests: + + pip install httpie + Now sync your database for the first time: python manage.py migrate @@ -159,6 +163,30 @@ We can now access our API, both from the command-line, using tools like `curl`.. ] } +Or with [httpie][httpie], a tastier version of `curl`... + + bash: http -a username:password http://127.0.0.1:8000/users/ --body + { + "count": 2, + "next": null, + "previous": null, + "results": [ + { + "email": "admin@example.com", + "groups": [], + "url": "http://localhost:8000/users/1/", + "username": "paul" + }, + { + "email": "tom@example.com", + "groups": [ ], + "url": "http://127.0.0.1:8000/users/2/", + "username": "tom" + } + ] + } + + Or directly through the browser... ![Quick start image][image] @@ -173,3 +201,4 @@ If you want to get a more in depth understanding of how REST framework fits toge [image]: ../img/quickstart.png [tutorial]: 1-serialization.md [guide]: ../#api-guide +[httpie]: https://github.com/jakubroztocil/httpie#installation -- cgit v1.2.3 From 515060a6ab71e1ef22f4a1e03cb23dbad28a7b23 Mon Sep 17 00:00:00 2001 From: phalt Date: Tue, 2 Dec 2014 10:16:41 +0000 Subject: Only show pip install for httpie --- docs/tutorial/1-serialization.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 3ef65116..dc4fddf9 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -332,16 +332,12 @@ Quit out of the shell... In another terminal window, we can test the server. -We could use `curl`, but let's use a nicer tool called [httpie][httpie] to test our server. It has much nicer formatting and makes our output easier to read. This is especially useful when testing. +We can test our API using using `curl` or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that. You can install httpie on all operating systems using pip: pip install httpie -It can also be installed through [Homebrew][brew] on Mac: - - brew install httpie - Finally, we can get a list of all of the snippets: http http://127.0.0.1:8000/snippets/ --body -- cgit v1.2.3 From a17d5d2b0bff535dc1d7dcbd36947648e7a0511f Mon Sep 17 00:00:00 2001 From: phalt Date: Tue, 2 Dec 2014 16:11:43 +0000 Subject: remove unsused link --- docs/tutorial/1-serialization.md | 1 - 1 file changed, 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index dc4fddf9..ba2a0c32 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -390,4 +390,3 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. [virtualenv]: http://www.virtualenv.org/en/latest/index.html [tut-2]: 2-requests-and-responses.md [httpie]: https://github.com/jakubroztocil/httpie#installation -[brew]: http://brew.sh -- cgit v1.2.3 From ab25d706c78627dfd582fe9d142ada510c4d6d90 Mon Sep 17 00:00:00 2001 From: Martin Tschammer Date: Wed, 3 Dec 2014 23:52:35 +0100 Subject: Renamed validated_attrs to validated_data to be more in line with other similar code. --- docs/tutorial/1-serialization.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index a3c19858..52c75d2c 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -110,21 +110,21 @@ The first thing we need to get started on our Web API is to provide a way of ser style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') - def create(self, validated_attrs): + def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ - return Snippet.objects.create(**validated_attrs) + return Snippet.objects.create(**validated_data) - def update(self, instance, validated_attrs): + def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ - instance.title = validated_attrs.get('title', instance.title) - instance.code = validated_attrs.get('code', instance.code) - instance.linenos = validated_attrs.get('linenos', instance.linenos) - instance.language = validated_attrs.get('language', instance.language) - instance.style = validated_attrs.get('style', instance.style) + instance.title = validated_data.get('title', instance.title) + instance.code = validated_data.get('code', instance.code) + instance.linenos = validated_data.get('linenos', instance.linenos) + instance.language = validated_data.get('language', instance.language) + instance.style = validated_data.get('style', instance.style) instance.save() return instance -- cgit v1.2.3 From fcbae5d99f93a28c9aac340bf2d4d2a3930e1a6a Mon Sep 17 00:00:00 2001 From: phalt Date: Thu, 4 Dec 2014 11:20:33 +0000 Subject: updates based on suggestions --- docs/tutorial/1-serialization.md | 9 ++++++--- docs/tutorial/2-requests-and-responses.md | 4 +++- docs/tutorial/quickstart.md | 11 +++++------ 3 files changed, 14 insertions(+), 10 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index ba2a0c32..5b1ae6e8 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -332,9 +332,9 @@ Quit out of the shell... In another terminal window, we can test the server. -We can test our API using using `curl` or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that. +We can test our API using using [curl][curl] or [httpie][httpie]. Httpie is a user friendly http client that's written in Python. Let's install that. -You can install httpie on all operating systems using pip: +You can install httpie using pip: pip install httpie @@ -363,8 +363,10 @@ Finally, we can get a list of all of the snippets: Or we can get a particular snippet by referencing its id: - http http://127.0.0.1:8000/snippets/2/ --body + http http://127.0.0.1:8000/snippets/2/ + HTTP/1.1 200 OK + ... { "id": 2, "title": "", @@ -390,3 +392,4 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. [virtualenv]: http://www.virtualenv.org/en/latest/index.html [tut-2]: 2-requests-and-responses.md [httpie]: https://github.com/jakubroztocil/httpie#installation +[curl]: http://curl.haxx.se diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index dcaf7c0c..08746cd7 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -127,8 +127,10 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][ We can get a list of all of the snippets, as before. - http http://127.0.0.1:8000/snippets/ --body + http http://127.0.0.1:8000/snippets/ + HTTP/1.1 200 OK + ... [ { "id": 1, diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 41e864cc..43220ce8 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -24,10 +24,6 @@ Create a new Django project named `tutorial`, then start a new app called `quick django-admin.py startapp quickstart cd .. -Optionally, install [httpie][httpie] for tastier HTTP requests: - - pip install httpie - Now sync your database for the first time: python manage.py migrate @@ -163,9 +159,12 @@ We can now access our API, both from the command-line, using tools like `curl`.. ] } -Or with [httpie][httpie], a tastier version of `curl`... +Or using the [httpie][httpie], command line tool... + + bash: http -a username:password http://127.0.0.1:8000/users/ - bash: http -a username:password http://127.0.0.1:8000/users/ --body + HTTP/1.1 200 OK + ... { "count": 2, "next": null, -- cgit v1.2.3 From 38e05e66c932fc2967cefbd88225bcdc2b0313a7 Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Thu, 4 Dec 2014 23:22:00 +0100 Subject: print() function works from Python 2.6 to 3.X --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 52c75d2c..b704996d 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -210,7 +210,7 @@ One nice property that serializers have is that you can inspect all the fields i >>> from snippets.serializers import SnippetSerializer >>> serializer = SnippetSerializer() - >>> print repr(serializer) # In python 3 use `print(repr(serializer))` + >>> print(repr(serializer)) SnippetSerializer(): id = IntegerField(label='ID', read_only=True) title = CharField(allow_blank=True, max_length=100, required=False) -- cgit v1.2.3 From 9d078be59ca5067d098263b1892740b44f7c41ee Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Thu, 4 Dec 2014 23:34:55 +0100 Subject: Fix the tutorial against the v3.0 --- docs/tutorial/1-serialization.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index b704996d..eb0a00c0 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -101,7 +101,7 @@ The first thing we need to get started on our Web API is to provide a way of ser class SnippetSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) - title = serializers.CharField(required=False, + title = serializers.CharField(required=False, allow_blank=True max_length=100) code = serializers.CharField(style={'type': 'textarea'}) linenos = serializers.BooleanField(required=False) @@ -181,7 +181,7 @@ Deserialization is similar. First we parse a stream into Python native datatype serializer = SnippetSerializer(data=data) serializer.is_valid() # True - serializer.object + serializer.save() # Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer. @@ -301,7 +301,7 @@ We'll also need a view which corresponds to an individual snippet, and can be us Finally we need to wire these views up. Create the `snippets/urls.py` file: - from django.conf.urls import patterns, url + from django.conf.urls import url from snippets import views urlpatterns = [ -- cgit v1.2.3 From e2b39088345e564a06ce332b740215600c29e481 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 5 Dec 2014 09:44:01 +0000 Subject: Fix quickstart tutorial --- docs/tutorial/quickstart.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 3e1ce0a9..d0703381 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -19,10 +19,9 @@ Create a new Django project named `tutorial`, then start a new app called `quick pip install djangorestframework # Set up a new project with a single application - django-admin.py startproject tutorial + django-admin.py startproject tutorial . cd tutorial django-admin.py startapp quickstart - cd .. Now sync your database for the first time: -- cgit v1.2.3 From 1b8c06aefe33f178610d2c4195a72637757698e8 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 5 Dec 2014 12:46:08 +0000 Subject: Style tweaks in examples --- docs/tutorial/1-serialization.md | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index eb0a00c0..fc1b87f9 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -16,7 +16,6 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on. - :::bash virtualenv env source env/bin/activate @@ -75,12 +74,8 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) - language = models.CharField(choices=LANGUAGE_CHOICES, - default='python', - max_length=100) - style = models.CharField(choices=STYLE_CHOICES, - default='friendly', - max_length=100) + language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) + style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) @@ -101,14 +96,11 @@ The first thing we need to get started on our Web API is to provide a way of ser class SnippetSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) - title = serializers.CharField(required=False, allow_blank=True - max_length=100) + title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={'type': 'textarea'}) linenos = serializers.BooleanField(required=False) - language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, - default='python') - style = serializers.ChoiceField(choices=STYLE_CHOICES, - default='friendly') + language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') + style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') def create(self, validated_data): """ -- cgit v1.2.3 From b7b0fd3e146648ba2dc03621edd979abaebcb3b3 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Fri, 5 Dec 2014 12:48:12 +0000 Subject: Added .validated_data usage. Closes #2214. --- docs/tutorial/1-serialization.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index fc1b87f9..3621f01b 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -173,6 +173,8 @@ Deserialization is similar. First we parse a stream into Python native datatype serializer = SnippetSerializer(data=data) serializer.is_valid() # True + serializer.validated_data + # OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]) serializer.save() # -- cgit v1.2.3 From e4820d611bb17e33bf466c2a6dedcce7548d8d21 Mon Sep 17 00:00:00 2001 From: Xavier Ordoquy Date: Sat, 6 Dec 2014 10:53:24 +0100 Subject: Fix the new Django default db name PrimaryKeyRelatedField now needs a queryset argument. urls now don't use urlpatterns. --- docs/tutorial/4-authentication-and-permissions.md | 4 ++-- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 4e4edeea..43c1953e 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -43,7 +43,7 @@ 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 + rm -f tmp.db db.sqlite3 rm -r snippets/migrations python manage.py makemigrations snippets python manage.py migrate @@ -59,7 +59,7 @@ Now that we've got some users to work with, we'd better add representations of t 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 diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 50552616..58422929 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -44,7 +44,7 @@ Instead of using a concrete generic view, we'll use the base class for represent As usual we need to add the new views that we've created in to our URLconf. We'll add a url pattern for our new API root in `snippets/urls.py`: - url(r'^$', 'api_root'), + url(r'^$', views.api_root), And then add a url pattern for the snippet highlights: -- cgit v1.2.3 From 8e9408115d0a3ab433078b82c9cc51f825eeac71 Mon Sep 17 00:00:00 2001 From: phalt Date: Mon, 8 Dec 2014 15:41:01 +0000 Subject: fixed indentations --- docs/tutorial/1-serialization.md | 8 +++++--- docs/tutorial/2-requests-and-responses.md | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 5b1ae6e8..5dcffcbd 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -340,9 +340,11 @@ You can install httpie using pip: Finally, we can get a list of all of the snippets: - http http://127.0.0.1:8000/snippets/ --body + http http://127.0.0.1:8000/snippets/ - [ + HTTP/1.1 200 OK + ... + [ { "id": 1, "title": "", @@ -367,7 +369,7 @@ Or we can get a particular snippet by referencing its id: HTTP/1.1 200 OK ... - { + { "id": 2, "title": "", "code": "print \"hello, world\"\n", diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 08746cd7..49e96d03 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -127,7 +127,7 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][ We can get a list of all of the snippets, as before. - http http://127.0.0.1:8000/snippets/ + http http://127.0.0.1:8000/snippets/ HTTP/1.1 200 OK ... -- cgit v1.2.3 From f3ebac061e7b5a67afe1d9440876afa804d3995d Mon Sep 17 00:00:00 2001 From: phalt Date: Mon, 8 Dec 2014 15:47:49 +0000 Subject: one last tabs / spaces! --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 5dcffcbd..538b0d93 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -365,7 +365,7 @@ Finally, we can get a list of all of the snippets: Or we can get a particular snippet by referencing its id: - http http://127.0.0.1:8000/snippets/2/ + http http://127.0.0.1:8000/snippets/2/ HTTP/1.1 200 OK ... -- cgit v1.2.3 From 4e9ebb5fe9eee2ef6f21718d9becfb8e94bbbe98 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 8 Dec 2014 16:38:17 +0000 Subject: cd back to parent directory --- docs/tutorial/quickstart.md | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index d0703381..f72fc7dd 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -22,6 +22,7 @@ Create a new Django project named `tutorial`, then start a new app called `quick django-admin.py startproject tutorial . cd tutorial django-admin.py startapp quickstart + cd .. Now sync your database for the first time: -- cgit v1.2.3 From 76956beab41cda7abdfb0aac714b35494f6ca3d5 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Tue, 9 Dec 2014 19:53:27 +0000 Subject: snippets relationship in tutorial should be read_only --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 58422929..57e3b6c5 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -85,7 +85,7 @@ We can easily re-write our existing serializers to use hyperlinking. In your `sn class UserSerializer(serializers.HyperlinkedModelSerializer): - snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail') + snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) class Meta: model = User -- cgit v1.2.3 From 9b88b5db694b4cc68b87c87d967f912a47fa5817 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Thu, 11 Dec 2014 09:54:55 +0000 Subject: Field->ReadOnlyField in tutorial docs --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 57e3b6c5..c21efd7f 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -75,7 +75,7 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add: class SnippetSerializer(serializers.HyperlinkedModelSerializer): - owner = serializers.Field(source='owner.username') + owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: -- cgit v1.2.3 From b951c74df2d10a7497152144baf5d105e804162f Mon Sep 17 00:00:00 2001 From: Jason Spafford Date: Mon, 15 Dec 2014 01:24:12 -0800 Subject: Made docs consistent --- docs/tutorial/2-requests-and-responses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 49e96d03..c0426969 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -181,7 +181,7 @@ Similarly, we can control the format of the request that we send, using the `Con "id": 4, "title": "", "code": "print 456", - "linenos": true, + "linenos": false, "language": "python", "style": "friendly" } -- cgit v1.2.3 From 1ba822010d0943c67c127f3f62e873b64348ef87 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Dec 2014 15:22:27 +0000 Subject: Highlight trailing '.' in command so it wont be missed. --- docs/tutorial/quickstart.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index c3f95994..a4474c34 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -19,7 +19,7 @@ Create a new Django project named `tutorial`, then start a new app called `quick pip install djangorestframework # Set up a new project with a single application - django-admin.py startproject tutorial . + django-admin.py startproject tutorial . # Note the trailing '.' character cd tutorial django-admin.py startapp quickstart cd .. -- cgit v1.2.3 From 530f7a21b3d28ddb24da036e0af6fd7b0a9a2304 Mon Sep 17 00:00:00 2001 From: Brent O'Connor Date: Wed, 17 Dec 2014 10:19:15 -0600 Subject: Fixed a typo --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index dea43cc0..20b9d889 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -200,7 +200,7 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') -One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following: +One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing it's representation. Open the Django shell with `python manage.py shell`, then try the following: >>> from snippets.serializers import SnippetSerializer >>> serializer = SnippetSerializer() -- cgit v1.2.3 From 90b8f9221e633797c5ab6a25e6c2a14805d459af Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 17 Dec 2014 16:23:00 +0000 Subject: Use six.BytesIO in tutorial. Closes #2296. --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index dea43cc0..aab5ce71 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -163,7 +163,7 @@ Deserialization is similar. First we parse a stream into Python native datatype # This import will use either `StringIO.StringIO` or `io.BytesIO` # as appropriate, depending on if we're running Python 2 or Python 3. - from rest_framework.compat import BytesIO + from django.utils.six import BytesIO stream = BytesIO(content) data = JSONParser().parse(stream) -- cgit v1.2.3 From eeb6e340644eba70b2fd41100db34b159ae6f091 Mon Sep 17 00:00:00 2001 From: Tymur Maryokhin Date: Wed, 17 Dec 2014 17:28:11 +0100 Subject: Docs/tutorial import fixes. Refs #2296 --- docs/tutorial/1-serialization.md | 2 -- 1 file changed, 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index b1baf0dd..ff507a2b 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -161,8 +161,6 @@ At this point we've translated the model instance into Python native datatypes. Deserialization is similar. First we parse a stream into Python native datatypes... - # This import will use either `StringIO.StringIO` or `io.BytesIO` - # as appropriate, depending on if we're running Python 2 or Python 3. from django.utils.six import BytesIO stream = BytesIO(content) -- cgit v1.2.3 From 4f33cfe1a00b410553ad9705354ada7ee8b52c01 Mon Sep 17 00:00:00 2001 From: Brent O'Connor Date: Wed, 17 Dec 2014 14:38:01 -0600 Subject: With httpie 0.8.0 the HTTP method has to come after the auth argument. --- docs/tutorial/4-authentication-and-permissions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index a6d27bf7..592c77e8 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -206,7 +206,7 @@ If we try to create a snippet without authenticating, we'll get an error: We can make a successful request by including the username and password of one of the users we created earlier. - http POST -a tom:password http://127.0.0.1:8000/snippets/ code="print 789" + http -a tom:password POST http://127.0.0.1:8000/snippets/ code="print 789" { "id": 5, -- cgit v1.2.3 From 7e9aac98fe2dca54778470030bf71b73b565f50d Mon Sep 17 00:00:00 2001 From: Brent O'Connor Date: Wed, 17 Dec 2014 16:54:04 -0600 Subject: The pre_save method no longer works. This resolved issue #2306 --- docs/tutorial/6-viewsets-and-routers.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 816e9da6..d55a60de 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -44,8 +44,8 @@ Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighl snippet = self.get_object() return Response(snippet.highlighted) - def pre_save(self, obj): - obj.owner = self.request.user + def perform_create(self, serializer): + serializer.save(owner=self.request.user) This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. -- cgit v1.2.3 From a8a3fedb5c52cc62c6ecf59c4138e9a6ecf04806 Mon Sep 17 00:00:00 2001 From: tanwanirahul Date: Fri, 19 Dec 2014 20:16:46 +0530 Subject: Add url_path documention for detail_route decorator --- docs/tutorial/6-viewsets-and-routers.md | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index cf37a260..8e4e22f0 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -53,6 +53,8 @@ Notice that we've also used the `@detail_route` decorator to create a custom act Custom actions which use the `@detail_route` decorator will respond to `GET` requests. We can use the `methods` argument if we wanted an action that responded to `POST` requests. +The URLs for custom actions by default depends on the method name itself. If you want to change the way url should be constructed, you can use `url_path` parameter of `@detail_route` and provide the string value for the same. + ## Binding ViewSets to URLs explicitly The handler methods only get bound to the actions when we define the URLConf. -- cgit v1.2.3 From 8f0fef4b75f5c999c13b5d37a263da3a3388142e Mon Sep 17 00:00:00 2001 From: Rahul Date: Fri, 19 Dec 2014 21:22:10 +0530 Subject: Updated documentation on url_path per suggestions. --- docs/tutorial/6-viewsets-and-routers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index 8e4e22f0..d2ee1102 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -53,7 +53,7 @@ Notice that we've also used the `@detail_route` decorator to create a custom act Custom actions which use the `@detail_route` decorator will respond to `GET` requests. We can use the `methods` argument if we wanted an action that responded to `POST` requests. -The URLs for custom actions by default depends on the method name itself. If you want to change the way url should be constructed, you can use `url_path` parameter of `@detail_route` and provide the string value for the same. +The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include url_path as a decorator keyword argument. ## Binding ViewSets to URLs explicitly -- cgit v1.2.3 From 336faf5a861fad2e4364a68fbf0747bef4457358 Mon Sep 17 00:00:00 2001 From: Rob Terhaar Date: Thu, 1 Jan 2015 21:01:16 -0500 Subject: fix widget style formatting --- docs/tutorial/1-serialization.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index ff507a2b..60a3d989 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -124,7 +124,7 @@ The first part of the serializer class defines the fields that get serialized/de A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`. -The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `style={'type': 'textarea'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. +The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `{'base_template': 'textarea.html'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. @@ -206,7 +206,7 @@ One nice property that serializers have is that you can inspect all the fields i SnippetSerializer(): id = IntegerField(label='ID', read_only=True) title = CharField(allow_blank=True, max_length=100, required=False) - code = CharField(style={'type': 'textarea'}) + code = CharField(style={'base_template': 'textarea.html'}) linenos = BooleanField(required=False) language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... -- cgit v1.2.3 From 8ccf5bcc0bb3455c0d71a0e0d845ef54489bb28e Mon Sep 17 00:00:00 2001 From: Travis Swientek Date: Fri, 9 Jan 2015 11:36:21 -0800 Subject: Tweaked a few issues in the tutorial documentation. --- docs/tutorial/1-serialization.md | 2 +- docs/tutorial/3-class-based-views.md | 2 +- docs/tutorial/4-authentication-and-permissions.md | 2 +- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 ++ 4 files changed, 5 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 60a3d989..41ff4d07 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -191,7 +191,7 @@ Our `SnippetSerializer` class is replicating a lot of information that's also co In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes. Let's look at refactoring our serializer using the `ModelSerializer` class. -Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` class. +Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following. class SnippetSerializer(serializers.ModelSerializer): class Meta: diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index 0a9ea3f1..abf82e49 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -64,7 +64,7 @@ That's looking good. Again, it's still pretty similar to the function based vie We'll also need to refactor our `urls.py` slightly now we're using class based views. - from django.conf.urls import patterns, url + from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from snippets import views diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 592c77e8..887d1e56 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -177,7 +177,7 @@ In the snippets app, create a new file, `permissions.py` # 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,) diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index c21efd7f..2841f03e 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -106,6 +106,8 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this: + from django.conf.urls import url, include + # API endpoints urlpatterns = format_suffix_patterns([ url(r'^$', views.api_root), -- cgit v1.2.3 From b0bc79ed4dade0636fc45bc001ef659aa664cd4a Mon Sep 17 00:00:00 2001 From: Eric Theise Date: Mon, 19 Jan 2015 14:49:36 -0800 Subject: correcting "it's" to "its" in Tutorial 1 --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 41ff4d07..80e869ea 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -198,7 +198,7 @@ Open the file `snippets/serializers.py` again, and replace the `SnippetSerialize model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') -One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing it's representation. Open the Django shell with `python manage.py shell`, then try the following: +One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following: >>> from snippets.serializers import SnippetSerializer >>> serializer = SnippetSerializer() -- cgit v1.2.3 From 90c9968a70e0a3d14cf4433cd356bcbdd30fce1b Mon Sep 17 00:00:00 2001 From: Michael Marvick Date: Sun, 25 Jan 2015 23:45:56 -0800 Subject: tutorial #1 incorrectly showed string of json instead of ReturnDict type from 'serializer.data', and also has a third item in the second usage --- docs/tutorial/1-serialization.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 80e869ea..458161d0 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -151,7 +151,7 @@ We've now got a few snippet instances to play with. Let's take a look at serial serializer = SnippetSerializer(snippet) serializer.data - # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'} + # ReturnDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]) At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. @@ -182,7 +182,8 @@ We can also serialize querysets instead of model instances. To do so we simply serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer.data - # [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}] + # [OrderedDict([('pk', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 3), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])] + ## Using ModelSerializers -- cgit v1.2.3 From 2a6937f381fe514e6cc9165c0aee200bf145788f Mon Sep 17 00:00:00 2001 From: Michael Marvick Date: Sun, 25 Jan 2015 23:46:27 -0800 Subject: tutorial #2 incorrectly showed /item.json instead of /item/.json for format suffixes --- docs/tutorial/2-requests-and-responses.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index c0426969..9315a664 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -96,7 +96,7 @@ Notice that we're no longer explicitly tying our requests or responses to a give ## Adding optional format suffixes to our URLs -To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url]. +To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4/.json][json-url]. Start by adding a `format` keyword argument to both of the views, like so. -- cgit v1.2.3 From 73bd0d539f24d45695615c25a072175c58a4cf98 Mon Sep 17 00:00:00 2001 From: Michael Marvick Date: Sun, 25 Jan 2015 23:47:01 -0800 Subject: tutorial #5 incorrectly referenced 'settings.py' instead of 'tutorial/settings.py' --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 2841f03e..740a4ce2 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -138,7 +138,7 @@ After adding all those names into our URLconf, our final `snippets/urls.py` file The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages. -We can change the default list style to use pagination, by modifying our `settings.py` file slightly. Add the following setting: +We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting: REST_FRAMEWORK = { 'PAGINATE_BY': 10 -- cgit v1.2.3 From aaa1fcd5d1137a8a32d4923a331032ffd9877975 Mon Sep 17 00:00:00 2001 From: José Padilla Date: Sun, 1 Feb 2015 16:18:02 -0400 Subject: Fixes #2493 --- docs/tutorial/1-serialization.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 80e869ea..ceb23a02 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -97,7 +97,7 @@ The first thing we need to get started on our Web API is to provide a way of ser class SnippetSerializer(serializers.Serializer): pk = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) - code = serializers.CharField(style={'type': 'textarea'}) + code = serializers.CharField(style={'base_template': 'textarea.html'}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') -- cgit v1.2.3 From 5bf803b6ed260d9afde47400b7d5e8912a16ecf6 Mon Sep 17 00:00:00 2001 From: Michael Marvick Date: Thu, 5 Feb 2015 19:42:36 -0800 Subject: Revert some of the changes made in 1-serialization.md --- docs/tutorial/1-serialization.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 458161d0..80e869ea 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -151,7 +151,7 @@ We've now got a few snippet instances to play with. Let's take a look at serial serializer = SnippetSerializer(snippet) serializer.data - # ReturnDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]) + # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'} At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. @@ -182,8 +182,7 @@ We can also serialize querysets instead of model instances. To do so we simply serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer.data - # [OrderedDict([('pk', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('pk', 3), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])] - + # [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}] ## Using ModelSerializers -- cgit v1.2.3 From 18cc0230bff436da2f26b2b25034cece32c9f5d0 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 4 Mar 2015 15:51:00 +0000 Subject: Clean up pagination attributes --- docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +- docs/tutorial/quickstart.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs/tutorial') diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 740a4ce2..91cdd6f1 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -141,7 +141,7 @@ The list views for users and code snippets could end up returning quite a lot of We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting: REST_FRAMEWORK = { - 'PAGINATE_BY': 10 + 'PAGE_SIZE': 10 } Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings. diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index a4474c34..fe0ecbc7 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -123,7 +123,7 @@ We'd also like to set a few global settings. We'd like to turn on pagination, a REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',), - 'PAGINATE_BY': 10 + 'PAGE_SIZE': 10 } Okay, we're done. -- cgit v1.2.3