From d4063eb02e31401252ca15b3aae50ed951d7869f Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 26 Oct 2012 12:46:31 +0100
Subject: Fix incorrect method signature in docs
---
docs/api-guide/generic-views.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 97b4441f..360ef1a2 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -30,7 +30,7 @@ For more complex cases you might also want to override various methods on the vi
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
- def get_paginate_by(self):
+ def get_paginate_by(self, queryset):
"""
Use smaller pagination for HTML representations.
"""
--
cgit v1.2.3
From c221bc6f6f239d958e89523c00686da595c68578 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 26 Oct 2012 17:30:45 +0200
Subject: Use context dict in HTMLRenderer
---
docs/api-guide/renderers.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index b6db376c..b5e2fe8f 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -130,7 +130,7 @@ An example of a view that uses `HTMLRenderer`:
def get(self, request, *args, **kwargs)
self.object = self.get_object()
- return Response(self.object, template_name='user_detail.html')
+ return Response({'user': self.object}, template_name='user_detail.html')
You can use `HTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
--
cgit v1.2.3
From 5180b725655e84712b103fbc280353d25048068b Mon Sep 17 00:00:00 2001
From: Jamie Matthews
Date: Sat, 27 Oct 2012 13:53:07 +0100
Subject: Documentation for function-based view decorators
---
docs/api-guide/views.md | 43 +++++++++++++++++++++++++++++++++++++++++--
1 file changed, 41 insertions(+), 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index e3fbadb2..c51860b5 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -118,9 +118,48 @@ You won't typically need to override this method.
>
> — [Nick Coghlan][cite2]
-REST framework also gives you to work with regular function based views...
+REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
+
+### api_view(http_method_names)
+
+The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
+
+ from rest_framework.decorators import api_view
+
+ @api_view(['GET'])
+ def hello_world(request):
+ return Response({"message": "Hello, world!"})
+
+
+This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings).
+
+To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `throttle_classes` decorator, passing a list of throttle classes:
+
+ from rest_framework.decorators import api_view, throttle_classes
+ from rest_framework.throttling import UserRateThrottle
+
+ class OncePerDayUserThrottle(UserRateThrottle):
+ rate = '1/day'
+
+ @api_view(['GET'])
+ @throttle_classes([OncePerDayUserThrottle])
+ def view(request):
+ return Response({"message": "Hello for today! See you tomorrow!"})
+
+These decorators correspond to the attributes set on `APIView` subclasses, described above.
+
+### renderer_classes(renderer_classes)
+
+### parser_classes(parser_classes)
+
+### authentication_classes(authentication_classes)
+
+### throttle_classes(throttle_classes)
+
+### permission_classes(permission_classes)
-**[TODO]**
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
+[settings]: api-guide/settings.md
+[throttling]: api-guide/throttling.md
--
cgit v1.2.3
From ec1429ffc8079e2f0fcc5af05882360689fca5bf Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 27 Oct 2012 17:27:12 +0200
Subject: Tweaks
---
docs/api-guide/views.md | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index c51860b5..9e661532 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -148,15 +148,15 @@ To override the default settings, REST framework provides a set of additional de
These decorators correspond to the attributes set on `APIView` subclasses, described above.
-### renderer_classes(renderer_classes)
+### @renderer_classes()
-### parser_classes(parser_classes)
+### @parser_classes()
-### authentication_classes(authentication_classes)
+### @authentication_classes()
-### throttle_classes(throttle_classes)
+### @throttle_classes()
-### permission_classes(permission_classes)
+### @permission_classes()
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
--
cgit v1.2.3
From cef379db065711bd2f1b0805d28a56f7a80cef37 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 27 Oct 2012 18:39:17 +0100
Subject: 2.0 Announcement
---
docs/api-guide/views.md | 23 +++++++++++++----------
1 file changed, 13 insertions(+), 10 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 9e661532..96ce3be7 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -120,7 +120,9 @@ You won't typically need to override this method.
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
-### api_view(http_method_names)
+## @api_view()
+
+**Signature:** `@api_view(http_method_names)
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
@@ -133,7 +135,9 @@ The core of this functionality is the `api_view` decorator, which takes a list o
This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings).
-To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `throttle_classes` decorator, passing a list of throttle classes:
+## API policy decorators
+
+To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
from rest_framework.decorators import api_view, throttle_classes
from rest_framework.throttling import UserRateThrottle
@@ -148,16 +152,15 @@ To override the default settings, REST framework provides a set of additional de
These decorators correspond to the attributes set on `APIView` subclasses, described above.
-### @renderer_classes()
-
-### @parser_classes()
-
-### @authentication_classes()
-
-### @throttle_classes()
+The available decorators are:
-### @permission_classes()
+* `@renderer_classes(...)`
+* `@parser_classes(...)`
+* `@authentication_classes(...)`
+* `@throttle_classes(...)`
+* `@permission_classes(...)`
+Each of these decorators takes a single argument which must be a list or tuple of classes.
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
--
cgit v1.2.3
From d995742afc09ff8d387751a6fe47b9686845740b Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 27 Oct 2012 20:04:33 +0100
Subject: Add AllowAny permission
---
docs/api-guide/permissions.md | 12 ++++++++++++
docs/api-guide/settings.md | 6 +++++-
2 files changed, 17 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index 0b7b32e9..d43b7bed 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -33,6 +33,12 @@ The default permission policy may be set globally, using the `DEFAULT_PERMISSION
)
}
+If not specified, this setting defaults to allowing unrestricted access:
+
+ 'DEFAULT_PERMISSION_CLASSES': (
+ 'rest_framework.permissions.AllowAny',
+ )
+
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
class ExampleView(APIView):
@@ -58,6 +64,12 @@ Or, if you're using the `@api_view` decorator with function based views.
# API Reference
+## AllowAny
+
+The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**.
+
+This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.
+
## IsAuthenticated
The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise.
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 21efc853..3556a5b1 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -72,7 +72,11 @@ Default:
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
-Default: `()`
+Default:
+
+ (
+ 'rest_framework.permissions.AllowAny',
+ )
## DEFAULT_THROTTLE_CLASSES
--
cgit v1.2.3
From 12c363c1fe237d0357e6020b44890926856b9191 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 18:12:56 +0000
Subject: TemplateHTMLRenderer, StaticHTMLRenderer
---
docs/api-guide/renderers.md | 40 +++++++++++++++++++++++++++++++---------
1 file changed, 31 insertions(+), 9 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index b5e2fe8f..5efb3610 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -106,12 +106,12 @@ If you are considering using `XML` for your API, you may want to consider implem
**.format**: `'.xml'`
-## HTMLRenderer
+## TemplateHTMLRenderer
Renders data to HTML, using Django's standard template rendering.
Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`.
-The HTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
+The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
The template name is determined by (in order of preference):
@@ -119,27 +119,49 @@ The template name is determined by (in order of preference):
2. An explicit `.template_name` attribute set on this class.
3. The return result of calling `view.get_template_names()`.
-An example of a view that uses `HTMLRenderer`:
+An example of a view that uses `TemplateHTMLRenderer`:
class UserInstance(generics.RetrieveUserAPIView):
"""
A view that returns a templated HTML representations of a given user.
"""
model = Users
- renderer_classes = (HTMLRenderer,)
+ renderer_classes = (TemplateHTMLRenderer,)
def get(self, request, *args, **kwargs)
self.object = self.get_object()
return Response({'user': self.object}, template_name='user_detail.html')
-You can use `HTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
+You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
-If you're building websites that use `HTMLRenderer` along with other renderer classes, you should consider listing `HTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
+If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
**.media_type**: `text/html`
**.format**: `'.html'`
+See also: `StaticHTMLRenderer`
+
+## StaticHTMLRenderer
+
+A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.
+
+An example of a view that uses `TemplateHTMLRenderer`:
+
+ @api_view(('GET',))
+ @renderer_classes((StaticHTMLRenderer,))
+ def simple_html_view(request):
+ data = '
Hello, world
'
+ return Response(data)
+
+You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
+
+**.media_type**: `text/html`
+
+**.format**: `'.html'`
+
+See also: `TemplateHTMLRenderer`
+
## BrowsableAPIRenderer
Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
@@ -207,7 +229,7 @@ In some cases you might want your view to use different serialization styles dep
For example:
@api_view(('GET',))
- @renderer_classes((HTMLRenderer, JSONRenderer))
+ @renderer_classes((TemplateHTMLRenderer, JSONRenderer))
def list_users(request):
"""
A view that can return JSON or HTML representations
@@ -215,9 +237,9 @@ For example:
"""
queryset = Users.objects.filter(active=True)
- if request.accepted_media_type == 'text/html':
+ if request.accepted_renderer.format == 'html':
# TemplateHTMLRenderer takes a context dict,
- # and additionally requiresa 'template_name'.
+ # and additionally requires a 'template_name'.
# It does not require serialization.
data = {'users': queryset}
return Response(data, template_name='list_users.html')
--
cgit v1.2.3
From 3906ff0df5d1972a7226a4fdd0eebce9a026befa Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 20:18:02 +0000
Subject: Improve fields docs
---
docs/api-guide/fields.md | 69 +++++++++++++++++++++++++++++++++++++++++++++---
1 file changed, 66 insertions(+), 3 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 7e117df7..bf80945d 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -12,6 +12,51 @@ Serializer fields handle converting between primative values and internal dataty
**Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`.
+---
+
+## Core arguments
+
+Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
+
+### `source`
+
+The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`.
+
+The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the `PaginationSerializer` class for an example.)
+
+Defaults to the name of the field.
+
+### `readonly`
+
+Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization.
+
+Defaults to `False`
+
+### `required`
+
+Normally an error will be raised if a field is not supplied during deserialization.
+Set to false if this field is not required to be present during deserialization.
+
+Defaults to `True`.
+
+### `default`
+
+If set, this gives the default value that will be used for the field if none is supplied. If not set the default behaviour is to not populate the attribute at all.
+
+### `validators`
+
+A list of Django validators that should be used to validate deserialized values.
+
+### `error_messages`
+
+A dictionary of error codes to error messages.
+
+### `widget`
+
+Used only if rendering the field to HTML.
+This argument sets the widget that should be used to render the field.
+
+
---
# Generic Fields
@@ -192,7 +237,7 @@ Then an example output format for a Bookmark instance would be:
## PrimaryKeyRelatedField
-As with `RelatedField` field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
+This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
`PrimaryKeyRelatedField` will represent the target of the field using it's primary key.
@@ -200,16 +245,34 @@ Be default, `PrimaryKeyRelatedField` is read-write, although you can change this
## ManyPrimaryKeyRelatedField
-As with `RelatedField` field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
+This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
-`PrimaryKeyRelatedField` will represent the target of the field using their primary key.
+`PrimaryKeyRelatedField` will represent the targets of the field using their primary key.
Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
## HyperlinkedRelatedField
+This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
+
+`HyperlinkedRelatedField` will represent the target of the field using a hyperlink. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
+
+Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
+
## ManyHyperlinkedRelatedField
+This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
+
+`ManyHyperlinkedRelatedField` will represent the targets of the field using hyperlinks. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
+
+Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
+
## HyperLinkedIdentityField
+This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
+
+You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the model.
+
+This field is always read-only.
+
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From 6e4ab09aae8295e4ef722d59894bc2934435ae46 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 20:21:45 +0000
Subject: readonly -> read_only
---
docs/api-guide/fields.md | 10 +++++-----
docs/api-guide/serializers.md | 4 ++--
2 files changed, 7 insertions(+), 7 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index bf80945d..8c3df067 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -26,7 +26,7 @@ The value `source='*'` has a special meaning, and is used to indicate that the e
Defaults to the name of the field.
-### `readonly`
+### `read_only`
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization.
@@ -241,7 +241,7 @@ This field can be applied to any "to-one" relationship, such as a `ForeignKey` f
`PrimaryKeyRelatedField` will represent the target of the field using it's primary key.
-Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
+Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## ManyPrimaryKeyRelatedField
@@ -249,7 +249,7 @@ This field can be applied to any "to-many" relationship, such as a `ManyToManyFi
`PrimaryKeyRelatedField` will represent the targets of the field using their primary key.
-Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
+Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## HyperlinkedRelatedField
@@ -257,7 +257,7 @@ This field can be applied to any "to-one" relationship, such as a `ForeignKey` f
`HyperlinkedRelatedField` will represent the target of the field using a hyperlink. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
-Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
+Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## ManyHyperlinkedRelatedField
@@ -265,7 +265,7 @@ This field can be applied to any "to-many" relationship, such as a `ManyToManyFi
`ManyHyperlinkedRelatedField` will represent the targets of the field using hyperlinks. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
-Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `readonly` flag.
+Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
## HyperLinkedIdentityField
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 057827d3..2338b879 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -190,7 +190,7 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit
You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class.
class AccountSerializer(serializers.ModelSerializer):
- url = CharField(source='get_absolute_url', readonly=True)
+ url = CharField(source='get_absolute_url', read_only=True)
group = NaturalKeyField()
class Meta:
@@ -246,7 +246,7 @@ When serializing objects using a nested representation any occurances of recursi
model = Account
def get_pk_field(self, model_field):
- return serializers.Field(readonly=True)
+ return serializers.Field(read_only=True)
def get_nested_field(self, model_field):
return serializers.ModelSerializer()
--
cgit v1.2.3
From 351382fe35f966c989b27add5bb04d0d983a99ee Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 20:43:43 +0000
Subject: nested -> depth
---
docs/api-guide/serializers.md | 76 +++++++++++++++++++++++++------------------
1 file changed, 45 insertions(+), 31 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 2338b879..902179ba 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -107,21 +107,21 @@ where some of the attributes of an object might not be simple datatypes such as
The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another.
class UserSerializer(serializers.Serializer):
- email = serializers.EmailField()
- username = serializers.CharField()
-
- def restore_object(self, attrs, instance=None):
- return User(**attrs)
-
+ email = serializers.Field()
+ username = serializers.Field()
class CommentSerializer(serializers.Serializer):
user = UserSerializer()
- title = serializers.CharField()
- content = serializers.CharField(max_length=200)
- created = serializers.DateTimeField()
-
- def restore_object(self, attrs, instance=None):
- return Comment(**attrs)
+ title = serializers.Field()
+ content = serializers.Field()
+ created = serializers.Field()
+
+---
+
+**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses.
+
+---
+
## Creating custom fields
@@ -225,40 +225,54 @@ For example:
## Specifiying nested serialization
-The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `nested` option:
+The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
exclude = ('id',)
- nested = True
+ depth = 1
-The `nested` option may be set to either `True`, `False`, or an integer value. If given an integer value it indicates the depth of relationships that should be traversed before reverting to a flat representation.
+The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
-When serializing objects using a nested representation any occurances of recursion will be recognised, and will fall back to using a flat representation.
+## Customising the default fields
-## Customising the default fields used by a ModelSerializer
+You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get__field` methods.
+Each of these methods may either return a field or serializer instance, or `None`.
+### get_pk_field
- class AccountSerializer(serializers.ModelSerializer):
- class Meta:
- model = Account
+**Signature**: `.get_pk_field(self, model_field)`
- def get_pk_field(self, model_field):
- return serializers.Field(read_only=True)
+Returns the field instance that should be used to represent the pk field.
+
+### get_nested_field
+
+**Signature**: `.get_nested_field(self, model_field)`
+
+Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
+
+### get_related_field
- def get_nested_field(self, model_field):
- return serializers.ModelSerializer()
+**Signature**: `.get_related_field(self, model_field, to_many=False)`
- def get_related_field(self, model_field, to_many=False):
- queryset = model_field.rel.to._default_manager
- if to_many:
- return serializers.ManyRelatedField(queryset=queryset)
- return serializers.RelatedField(queryset=queryset)
+Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero.
+
+### get_field
+
+**Signature**: `.get_field(self, model_field)`
+
+Returns the field instance that should be used for non-relational, non-pk fields.
+
+### Example:
+
+The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
+
+ class NoPKModelSerializer(serializers.ModelSerializer):
+ def get_pk_field(self, model_field):
+ return None
- def get_field(self, model_field):
- return serializers.ModelField(model_field=model_field)
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
--
cgit v1.2.3
From 8d2774dc972ff5144d8ac0450c7f91ade2556ae0 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:07:42 +0100
Subject: fixed api_view decorator useage
---
docs/api-guide/parsers.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index ac904720..59f00f99 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -37,7 +37,7 @@ You can also set the renderers used for an individual view, using the `APIView`
Or, if you're using the `@api_view` decorator with function based views.
- @api_view(('POST',)),
+ @api_view(['POST'])
@parser_classes((YAMLParser,))
def example_view(request, format=None):
"""
--
cgit v1.2.3
From 842c8b4da4a556f7f4f337d482b2f039de3770ee Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:12:21 +0100
Subject: add missing "`" for code formatting
---
docs/api-guide/views.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 96ce3be7..5b072827 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -122,7 +122,7 @@ REST framework also allows you to work with regular function based views. It pro
## @api_view()
-**Signature:** `@api_view(http_method_names)
+**Signature:** `@api_view(http_method_names)`
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
--
cgit v1.2.3
From 72f3a7e4a7e07035f428bf2f8ce8ad31aa85f297 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:13:56 +0100
Subject: add missing semicolon
---
docs/api-guide/settings.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 3556a5b1..a3668e2a 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -42,7 +42,7 @@ Default:
(
'rest_framework.renderers.JSONRenderer',
- 'rest_framework.renderers.BrowsableAPIRenderer'
+ 'rest_framework.renderers.BrowsableAPIRenderer',
'rest_framework.renderers.TemplateHTMLRenderer'
)
--
cgit v1.2.3
From 46e546ff2319fc2cf85279deee1ce2140e0c7f45 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:20:14 +0100
Subject: fixed missplaced semicolon
---
docs/api-guide/throttling.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index d54433b1..56f16226 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -32,8 +32,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttles.AnonThrottle',
- 'rest_framework.throttles.UserThrottle',
- )
+ 'rest_framework.throttles.UserThrottle'
+ ),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
--
cgit v1.2.3
From 5164f5d7978e68ff3e68eaab5d30faea21241fc8 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:21:27 +0100
Subject: fixed missplaced semicolon
---
docs/api-guide/throttling.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index 56f16226..c8769a10 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -102,8 +102,8 @@ For example, multiple user throttle rates could be implemented by using the foll
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'example.throttles.BurstRateThrottle',
- 'example.throttles.SustainedRateThrottle',
- )
+ 'example.throttles.SustainedRateThrottle'
+ ),
'DEFAULT_THROTTLE_RATES': {
'burst': '60/min',
'sustained': '1000/day'
--
cgit v1.2.3
From 741b387f35a3f5daa98424d29fea4325898b7ff6 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:22:20 +0100
Subject: fixed missplaced semicolon
---
docs/api-guide/throttling.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index c8769a10..bfda7079 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -136,8 +136,8 @@ For example, given the following views...
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
- 'rest_framework.throttles.ScopedRateThrottle',
- )
+ 'rest_framework.throttles.ScopedRateThrottle'
+ ),
'DEFAULT_THROTTLE_RATES': {
'contacts': '1000/day',
'uploads': '20/day'
--
cgit v1.2.3
From 73cf859e26608e1310c07df789553fa2b6cd1f8b Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:23:25 +0100
Subject: add missing whitespace
---
docs/api-guide/permissions.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index d43b7bed..1a746fb6 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -78,7 +78,7 @@ This permission is suitable if you want your API to only be accessible to regist
## IsAdminUser
-The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff`is `True` in which case permission will be allowed.
+The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed.
This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.
--
cgit v1.2.3
From ff4804a36079f9c1d480a788397af3a7f8391371 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:25:17 +0100
Subject: fix api_view decorator useage
---
docs/api-guide/authentication.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 7bad4867..889d16c0 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -50,7 +50,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi
Or, if you're using the `@api_view` decorator with function based views.
- @api_view(('GET',)),
+ @api_view(['GET'])
@authentication_classes((SessionAuthentication, UserBasicAuthentication))
@permissions_classes((IsAuthenticated,))
def example_view(request, format=None):
--
cgit v1.2.3
From 2de89f2d53c4b06baca8df218c8de959af69a006 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:29:45 +0100
Subject: remove empty rows
---
docs/api-guide/serializers.md | 2 --
1 file changed, 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 902179ba..c88b9b0c 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -135,7 +135,6 @@ Let's look at an example of serializing a class that represents an RGB color val
"""
A color represented in the RGB colorspace.
"""
-
def __init__(self, red, green, blue):
assert(red >= 0 and green >= 0 and blue >= 0)
assert(red < 256 and green < 256 and blue < 256)
@@ -145,7 +144,6 @@ Let's look at an example of serializing a class that represents an RGB color val
"""
Color objects are serialized into "rgb(#, #, #)" notation.
"""
-
def to_native(self, obj):
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
--
cgit v1.2.3
From 586584201967d9810f649def51cef577c65d50fb Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 09:32:11 +0100
Subject: fixed api_view decorator useage
---
docs/api-guide/renderers.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 5efb3610..c3d12ddb 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -42,7 +42,7 @@ You can also set the renderers used for an individual view, using the `APIView`
Or, if you're using the `@api_view` decorator with function based views.
- @api_view(('GET',)),
+ @api_view(['GET'])
@renderer_classes((JSONRenderer, JSONPRenderer))
def user_count_view(request, format=None):
"""
--
cgit v1.2.3
From 7f7f0b6ffbae2c166bb87431b33803c9e695e251 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Wed, 31 Oct 2012 10:41:56 +0100
Subject: added missing semicolon
---
docs/api-guide/settings.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index a3668e2a..4f87b30d 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -13,7 +13,7 @@ For example your project's `settings.py` file might include something like this:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.YAMLRenderer',
- )
+ ),
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.YAMLParser',
)
--
cgit v1.2.3
From 96dc9ce1ad15275944a5fd9389843a30c6aff3c6 Mon Sep 17 00:00:00 2001
From: Otto Yiu
Date: Wed, 31 Oct 2012 21:27:21 -0700
Subject: Fixing documentation on auth/throttling guides
---
docs/api-guide/authentication.md | 6 +++---
docs/api-guide/throttling.md | 6 +++---
2 files changed, 6 insertions(+), 6 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 889d16c0..3137b9d4 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -30,7 +30,7 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
- 'rest_framework.authentication.UserBasicAuthentication',
+ 'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
@@ -38,7 +38,7 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
class ExampleView(APIView):
- authentication_classes = (SessionAuthentication, UserBasicAuthentication)
+ authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
def get(self, request, format=None):
@@ -51,7 +51,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi
Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET'])
- @authentication_classes((SessionAuthentication, UserBasicAuthentication))
+ @authentication_classes((SessionAuthentication, BasicAuthentication))
@permissions_classes((IsAuthenticated,))
def example_view(request, format=None):
content = {
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index bfda7079..b03bc9e0 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -31,8 +31,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
- 'rest_framework.throttles.AnonThrottle',
- 'rest_framework.throttles.UserThrottle'
+ 'rest_framework.throttling.AnonRateThrottle',
+ 'rest_framework.throttling.UserRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
@@ -136,7 +136,7 @@ For example, given the following views...
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
- 'rest_framework.throttles.ScopedRateThrottle'
+ 'rest_framework.throttling.ScopedRateThrottle'
),
'DEFAULT_THROTTLE_RATES': {
'contacts': '1000/day',
--
cgit v1.2.3
From 062f5caef3dcb76e19f9eed59779f45849a166a1 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Thu, 1 Nov 2012 23:40:34 +0000
Subject: Tweaks fields docs, and fix 2.0.1 version.
---
docs/api-guide/fields.md | 42 +++++++++++++++++++++++-------------------
1 file changed, 23 insertions(+), 19 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 8c3df067..86460b4b 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -235,44 +235,48 @@ Then an example output format for a Bookmark instance would be:
'url': u'https://www.djangoproject.com/'
}
-## PrimaryKeyRelatedField
+## PrimaryKeyRelatedField / ManyPrimaryKeyRelatedField
-This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
+`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
-`PrimaryKeyRelatedField` will represent the target of the field using it's primary key.
+Be default these fields read-write, although you can change this behaviour using the `read_only` flag.
-Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
+**Arguments**:
-## ManyPrimaryKeyRelatedField
+* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
-This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
+## SlugRelatedField / ManySlugRelatedField
-`PrimaryKeyRelatedField` will represent the targets of the field using their primary key.
+`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
-Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
+Be default these fields read-write, although you can change this behaviour using the `read_only` flag.
-## HyperlinkedRelatedField
+**Arguments**:
-This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
+* `slug_field` - The field on the target that should used as the representation. This should be a field that uniquely identifies any given instance. For example, `username`.
+* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
-`HyperlinkedRelatedField` will represent the target of the field using a hyperlink. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
+## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
-Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
-
-## ManyHyperlinkedRelatedField
+`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
-This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
+Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
-`ManyHyperlinkedRelatedField` will represent the targets of the field using hyperlinks. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
+**Arguments**:
-Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
## HyperLinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
-You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the model.
-
This field is always read-only.
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From b7b942c5991e677e7df621c00befb075d06edd61 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 5 Nov 2012 10:53:20 +0000
Subject: Swap position of `instance` and `data` keyword arguments.
---
docs/api-guide/serializers.md | 29 ++++++++++++++++++++++-------
1 file changed, 22 insertions(+), 7 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index c88b9b0c..ee7f72dd 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -47,7 +47,7 @@ The first part of serializer class defines the fields that get serialized/deseri
We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class.
- serializer = CommentSerializer(instance=comment)
+ serializer = CommentSerializer(comment)
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
@@ -65,20 +65,29 @@ Deserialization is similar. First we parse a stream into python native datatype
...then we restore those native datatypes into a fully populated object instance.
- serializer = CommentSerializer(data)
+ serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
serializer.object
#
>>> serializer.deserialize('json', stream)
+When deserializing data, we can either create a new instance, or update an existing instance.
+
+ serializer = CommentSerializer(data=data) # Create new instance
+ serializer = CommentSerializer(comment, data=data) # Update `instance`
+
## Validation
When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages.
### Field-level validation
-You can specify custom field-level validation by adding `validate_()` methods to your `Serializer` subclass. These are analagous to `clean_` methods on Django forms, but accept slightly different arguments. They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). Your `validate_` methods should either just return the attrs dictionary or raise a `ValidationError`. For example:
+You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are analagous to `.clean_` methods on Django forms, but accept slightly different arguments.
+
+They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided).
+
+Your `validate_` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example:
from rest_framework import serializers
@@ -88,16 +97,22 @@ You can specify custom field-level validation by adding `validate_()`
def validate_title(self, attrs, source):
"""
- Check that the blog post is about Django
+ Check that the blog post is about Django.
"""
value = attrs[source]
- if "Django" not in value:
+ if "django" not in value.lower():
raise serializers.ValidationError("Blog post is not about Django")
return attrs
-### Final cross-field validation
+### Object-level validation
+
+To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`.
+
+## Saving object state
+
+Serializers also include a `.save()` method that you can override if you want to provide a method of persisting the state of a deserialized object. The default behavior of the method is to simply call `.save()` on the deserialized object instance.
-To do any other validation that requires access to multiple fields, add a method called `validate` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`.
+The generic views provided by REST framework call the `.save()` method when updating or creating entities.
## Dealing with nested objects
--
cgit v1.2.3
From 85b176cf47cd0d4f392ee0a4bae971c709dbfddc Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 5 Nov 2012 16:51:49 +0100
Subject: added docs
---
docs/api-guide/fields.md | 2 ++
1 file changed, 2 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 86460b4b..3126c0c2 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -267,6 +267,8 @@ Be default, `HyperlinkedRelatedField` is read-write, although you can change thi
* `view_name` - The view name that should be used as the target of the relationship. **required**.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
+* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is `slug`
+* `slug_field` - The field on the target that should be used for the lookup. Default is `slug`
## HyperLinkedIdentityField
--
cgit v1.2.3
From 1418d104a86a0c861a9d3b9831f7bb98b0891f57 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 5 Nov 2012 16:44:26 +0000
Subject: Tweak related field docs now that queryset is no longer required.
---
docs/api-guide/fields.md | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 3126c0c2..fe621335 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -243,7 +243,7 @@ Be default these fields read-write, although you can change this behaviour using
**Arguments**:
-* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
## SlugRelatedField / ManySlugRelatedField
@@ -254,7 +254,7 @@ Be default these fields read-write, although you can change this behaviour using
**Arguments**:
* `slug_field` - The field on the target that should used as the representation. This should be a field that uniquely identifies any given instance. For example, `username`.
-* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
@@ -266,9 +266,9 @@ Be default, `HyperlinkedRelatedField` is read-write, although you can change thi
* `view_name` - The view name that should be used as the target of the relationship. **required**.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `queryset` - All relational fields must either set a queryset, or set `read_only=True`
-* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is `slug`
-* `slug_field` - The field on the target that should be used for the lookup. Default is `slug`
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
+* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
## HyperLinkedIdentityField
--
cgit v1.2.3
From 455a8cedcf5aa1f265ae95d4f3bff359d51910c0 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 5 Nov 2012 17:03:22 +0000
Subject: Tweaks
---
docs/api-guide/fields.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index fe621335..411f7944 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -239,7 +239,7 @@ Then an example output format for a Bookmark instance would be:
`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
-Be default these fields read-write, although you can change this behaviour using the `read_only` flag.
+By default these fields are read-write, although you can change this behaviour using the `read_only` flag.
**Arguments**:
@@ -249,18 +249,18 @@ Be default these fields read-write, although you can change this behaviour using
`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
-Be default these fields read-write, although you can change this behaviour using the `read_only` flag.
+By default these fields read-write, although you can change this behaviour using the `read_only` flag.
**Arguments**:
-* `slug_field` - The field on the target that should used as the representation. This should be a field that uniquely identifies any given instance. For example, `username`.
+* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
-Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
+By default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
**Arguments**:
--
cgit v1.2.3
From b19c58ae17ee54a3a8d193608660d96fd52f83f0 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 6 Nov 2012 10:44:19 +0000
Subject: Support for HTML error templates. Fixes #319.
---
docs/api-guide/renderers.md | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index c3d12ddb..374ff0ab 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -257,6 +257,21 @@ In [the words of Roy Fielding][quote], "A REST API should spend almost all of it
For good examples of custom media types, see GitHub's use of a custom [application/vnd.github+json] media type, and Mike Amundsen's IANA approved [application/vnd.collection+json] JSON-based hypermedia.
+## HTML error views
+
+Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an `Http404` or `PermissionDenied` exception, or a subclass of `APIException`.
+
+If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer` and an exception is raised, the behavior is slightly different, and mirrors [Django's default handling of error views][django-error-views].
+
+Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence.
+
+* Load and render a template named `{status_code}.html`.
+* Load and render a template named `api_exception.html`.
+* Render the HTTP status code and text, for example "404 Not Found".
+
+Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
+
+
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
@@ -265,3 +280,4 @@ For good examples of custom media types, see GitHub's use of a custom [applicati
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
+[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
\ No newline at end of file
--
cgit v1.2.3
From 2c52a2581f690eca62a203d9b5344ac39b43ba74 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 6 Nov 2012 17:02:34 +0100
Subject: added slug support for HyperlinkedIdentityField
---
docs/api-guide/fields.md | 2 ++
1 file changed, 2 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 411f7944..2a8949a1 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -280,5 +280,7 @@ This field is always read-only.
* `view_name` - The view name that should be used as the target of the relationship. **required**.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
+* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From 6d3bb67aa654d5f4c555746655a312000422d474 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 6 Nov 2012 17:11:52 +0000
Subject: Add pk_url_kwarg to hyperlinked fields
---
docs/api-guide/fields.md | 2 ++
1 file changed, 2 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 2a8949a1..0485b158 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -268,6 +268,7 @@ By default, `HyperlinkedRelatedField` is read-write, although you can change thi
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
+* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
## HyperLinkedIdentityField
@@ -281,6 +282,7 @@ This field is always read-only.
* `view_name` - The view name that should be used as the target of the relationship. **required**.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
+* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From 4136b7e44b85c7c887ab0c4379288512aa67fc64 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 6 Nov 2012 21:11:05 +0100
Subject: fixed typo in html status code
---
docs/api-guide/status-codes.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md
index 401f45ce..b50c96ae 100644
--- a/docs/api-guide/status-codes.md
+++ b/docs/api-guide/status-codes.md
@@ -87,7 +87,7 @@ Response status codes beginning with the digit "5" indicate cases in which the s
HTTP_503_SERVICE_UNAVAILABLE
HTTP_504_GATEWAY_TIMEOUT
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
- HTTP_511_NETWORD_AUTHENTICATION_REQUIRED
+ HTTP_511_NETWORK_AUTHENTICATION_REQUIRED
[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt
--
cgit v1.2.3
From e02a8470e8d32348a9bd7714e1f27cf6e55b5cda Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 6 Nov 2012 21:18:49 +0100
Subject: fixed typo
---
docs/api-guide/serializers.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index ee7f72dd..0cdae1ce 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -190,7 +190,7 @@ As an example, let's create a field that can be used represent the class name of
# ModelSerializers
Often you'll want serializer classes that map closely to model definitions.
-The `ModelSerializer` class lets you automatically create a Serializer class with fields that corrospond to the Model fields.
+The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields.
class AccountSerializer(serializers.ModelSerializer):
class Meta:
--
cgit v1.2.3
From 47b534a13e42d498629bf9522225633122c563d5 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 7 Nov 2012 21:07:24 +0000
Subject: Make filtering optional, and pluggable.
---
docs/api-guide/filtering.md | 114 ++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 114 insertions(+)
create mode 100644 docs/api-guide/filtering.md
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
new file mode 100644
index 00000000..7f6a9c97
--- /dev/null
+++ b/docs/api-guide/filtering.md
@@ -0,0 +1,114 @@
+# Filtering
+
+> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
+>
+> — [Django documentation][cite]
+
+The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
+
+The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method.
+
+Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
+
+## Filtering against the current user
+
+You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.
+
+You can do so by filtering based on the value of `request.user`.
+
+For example:
+
+ class PurchaseList(generics.ListAPIView)
+ model = Purchase
+ serializer_class = PurchaseSerializer
+
+ def get_queryset(self):
+ """
+ This view should return a list of all the purchases
+ for the currently authenticated user.
+ """
+ user = self.request.user
+ return Purchase.objects.filter(purchaser=user)
+
+
+## Filtering against the URL
+
+Another style of filtering might involve restricting the queryset based on some part of the URL.
+
+For example if your URL config contained an entry like this:
+
+ url('^purchases/(?P.+)/$', PurchaseList.as_view()),
+
+You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
+
+ class PurchaseList(generics.ListAPIView)
+ model = Purchase
+ serializer_class = PurchaseSerializer
+
+ def get_queryset(self):
+ """
+ This view should return a list of all the purchases for
+ the user as determined by the username portion of the URL.
+ """
+ username = self.kwargs['username']
+ return Purchase.objects.filter(purchaser__username=username)
+
+## Filtering against query parameters
+
+A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.
+
+We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
+
+ class PurchaseList(generics.ListAPIView)
+ model = Purchase
+ serializer_class = PurchaseSerializer
+
+ def get_queryset(self):
+ """
+ Optionally restricts the returned purchases to a given user,
+ by filtering against a `username` query parameter in the URL.
+ """
+ queryset = Purchase.objects.all()
+ username = self.request.QUERY_PARAMS.get('username', None):
+ if username is not None:
+ queryset = queryset.filter(purchaser__username=username)
+ return queryset
+
+# Generic Filtering
+
+As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters.
+
+REST framework supports pluggable backends to implement filtering, and includes a default implementation which uses the [django-filter] package.
+
+To use REST framework's default filtering backend, first install `django-filter`.
+
+ pip install -e git+https://github.com/alex/django-filter.git#egg=django-filter
+
+**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon.
+
+## Specifying filter fields
+
+**TODO**: Document setting `.filter_fields` on the view.
+
+## Specifying a FilterSet
+
+**TODO**: Document setting `.filter_class` on the view.
+
+**TODO**: Note support for `lookup_type`, double underscore relationship spanning, and ordering.
+
+# Custom generic filtering
+
+You can also provide your own generic filtering backend, or write an installable app for other developers to use.
+
+To do so overide `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method.
+
+To install the filter, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
+
+For example:
+
+ REST_FRAMEWORK = {
+ 'FILTER_BACKEND': 'custom_filters.CustomFilterBackend'
+ }
+
+[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
+[django-filter]: https://github.com/alex/django-filter
\ No newline at end of file
--
cgit v1.2.3
From 34c5fb0cc682831822ce77379e8211ec02349897 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 7 Nov 2012 21:28:10 +0000
Subject: Add filtering into documentation
---
docs/api-guide/filtering.md | 8 ++++++++
1 file changed, 8 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index 7f6a9c97..ea1e7d23 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -1,3 +1,5 @@
+
+
# Filtering
> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
@@ -74,6 +76,8 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
queryset = queryset.filter(purchaser__username=username)
return queryset
+---
+
# Generic Filtering
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters.
@@ -96,6 +100,10 @@ To use REST framework's default filtering backend, first install `django-filter`
**TODO**: Note support for `lookup_type`, double underscore relationship spanning, and ordering.
+**TODO**: Note that overiding `get_queryset()` can be used together with generic filtering
+
+---
+
# Custom generic filtering
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
--
cgit v1.2.3
From 0089f0faa716bd37ca29f9f2db98b4ab273e01f1 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Thu, 8 Nov 2012 20:43:15 +0000
Subject: Add media_type to example file parser
---
docs/api-guide/parsers.md | 1 +
1 file changed, 1 insertion(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 59f00f99..185b616c 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -140,6 +140,7 @@ For example:
"""
A naive raw file upload parser.
"""
+ media_type = '*/*' # Accept anything
def parse(self, stream, media_type=None, parser_context=None):
content = stream.read()
--
cgit v1.2.3
From bc6f2a170306fbc1cba3a4e504a908ebc72d54b7 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Thu, 8 Nov 2012 21:46:53 +0000
Subject: Make default FILTER_BACKEND = None
---
docs/api-guide/filtering.md | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index ea1e7d23..ca901b03 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -82,17 +82,19 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters.
-REST framework supports pluggable backends to implement filtering, and includes a default implementation which uses the [django-filter] package.
+REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package.
To use REST framework's default filtering backend, first install `django-filter`.
pip install -e git+https://github.com/alex/django-filter.git#egg=django-filter
-**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon.
+You must also set the filter backend to `DjangoFilterBackend` in your settings:
-## Specifying filter fields
+ REST_FRAMEWORK = {
+ 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend'
+ }
-**TODO**: Document setting `.filter_fields` on the view.
+**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon.
## Specifying a FilterSet
@@ -100,6 +102,10 @@ To use REST framework's default filtering backend, first install `django-filter`
**TODO**: Note support for `lookup_type`, double underscore relationship spanning, and ordering.
+## Specifying filter fields
+
+**TODO**: Document setting `.filter_fields` on the view.
+
**TODO**: Note that overiding `get_queryset()` can be used together with generic filtering
---
--
cgit v1.2.3
From ff1234b711b8dfb7dc1cc539fa9d2b6fd2477825 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 9 Nov 2012 13:05:36 +0000
Subject: Updated filteing docs.
---
docs/api-guide/filtering.md | 69 +++++++++++++++++++++++++++++++++++++++------
1 file changed, 60 insertions(+), 9 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index ca901b03..e49ea420 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -30,7 +30,7 @@ For example:
for the currently authenticated user.
"""
user = self.request.user
- return Purchase.objects.filter(purchaser=user)
+ return Purchase.objects.filter(purchaser=user)
## Filtering against the URL
@@ -96,27 +96,76 @@ You must also set the filter backend to `DjangoFilterBackend` in your settings:
**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon.
+## Specifying filter fields
+
+If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against.
+
+ class ProductList(generics.ListAPIView):
+ model = Product
+ serializer_class = ProductSerializer
+ filter_fields = ('category', 'in_stock')
+
+This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as:
+
+ http://example.com/api/products?category=clothing&in_stock=True
+
## Specifying a FilterSet
-**TODO**: Document setting `.filter_class` on the view.
+For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example:
-**TODO**: Note support for `lookup_type`, double underscore relationship spanning, and ordering.
+ class ProductFilter(django_filters.FilterSet):
+ min_price = django_filters.NumberFilter(lookup_type='gte')
+ max_price = django_filters.NumberFilter(lookup_type='lte')
+ class Meta:
+ model = Product
+ fields = ['category', 'in_stock', 'min_price', 'max_price']
-## Specifying filter fields
+ class ProductList(generics.ListAPIView):
+ model = Product
+ serializer_class = ProductSerializer
+ filter_class = ProductFilter
-**TODO**: Document setting `.filter_fields` on the view.
+Which will allow you to make requests such as:
-**TODO**: Note that overiding `get_queryset()` can be used together with generic filtering
+ http://example.com/api/products?category=clothing&max_price=10.00
+For more details on using filter sets see the [django-filter documentation][django-filter-docs].
+
+---
+
+**Hints & Tips**
+
+* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'FILTER_BACKEND'` setting.
+* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].)
+* `django-filter` supports filtering across relationships, using Django's double-underscore syntax.
+
+---
+
+## Overriding the intial queryset
+
+Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
+
+ class PurchasedProductsList(generics.ListAPIView):
+ """
+ Return a list of all the products that the authenticated
+ user has ever purchased, with optional filtering.
+ """
+ model = Product
+ serializer_class = ProductSerializer
+ filter_class = ProductFilter
+
+ def get_queryset(self):
+ user = self.request.user
+ return user.purchase_set.all()
---
# Custom generic filtering
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
-To do so overide `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method.
+To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method.
-To install the filter, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
+To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
For example:
@@ -125,4 +174,6 @@ For example:
}
[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
-[django-filter]: https://github.com/alex/django-filter
\ No newline at end of file
+[django-filter]: https://github.com/alex/django-filter
+[django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html
+[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py
\ No newline at end of file
--
cgit v1.2.3
From 71ef58e154330924ec9d22b1736926ce9d373efe Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 9 Nov 2012 13:17:00 +0000
Subject: Typo
---
docs/api-guide/filtering.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index e49ea420..92e312ab 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -141,7 +141,7 @@ For more details on using filter sets see the [django-filter documentation][djan
---
-## Overriding the intial queryset
+## Overriding the initial queryset
Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this:
--
cgit v1.2.3
From 9aaeeacdfebc244850e82469e4af45af252cca4d Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 9 Nov 2012 13:39:40 +0000
Subject: Minor docs tweak.
---
docs/api-guide/filtering.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index 92e312ab..14ab9a26 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -163,7 +163,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
You can also provide your own generic filtering backend, or write an installable app for other developers to use.
-To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method.
+To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
--
cgit v1.2.3
From e224061189a6a5ea2c063f3820239eed6c3a88fb Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 9 Nov 2012 17:01:20 +0000
Subject: Support for `read_only_fields` on `ModelSerializer` classes
---
docs/api-guide/serializers.md | 9 +++++++++
1 file changed, 9 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 0cdae1ce..a9589144 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -248,6 +248,15 @@ The default `ModelSerializer` uses primary keys for relationships, but you can a
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
+## Specifying which fields should be read-only
+
+You may wish to specify multiple fields as read-only. Instead of adding each field explicitely with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
+
+ class AccountSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Account
+ read_only_fields = ('created', 'modified')
+
## Customising the default fields
You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get__field` methods.
--
cgit v1.2.3
From 5967f15f7f5c87987ab60e4b7dc682b06f3ab511 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Wed, 14 Nov 2012 16:11:35 +0100
Subject: updated docs
---
docs/api-guide/generic-views.md | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 360ef1a2..9e5119cb 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -147,6 +147,10 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q
Should be mixed in with [MultipleObjectAPIView].
+**Arguments**:
+
+* `page_size` - Hook to adjust page_size per request.
+
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
--
cgit v1.2.3
From 1e83b60a43c26db921d6910092362feb3a76500d Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Wed, 14 Nov 2012 18:00:59 +0100
Subject: added description how to use the auth token
---
docs/api-guide/authentication.md | 15 +++++++++++++++
1 file changed, 15 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 3137b9d4..cb1e2645 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -97,6 +97,21 @@ If successfully authenticated, `TokenAuthentication` provides the following cred
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
+If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
+
+ @receiver(post_save, sender=User)
+ def create_auth_token(sender, instance=None, created=False, **kwargs):
+ if created:
+ Token.objects.create(user=instance)
+
+If you've already created some User`'s, you can run a script like this.
+
+ from django.contrib.auth.models import User
+ from rest_framework.authtoken.models import Token
+
+ for user in User.objects.all():
+ Token.objects.get_or_create(user=user)
+
## OAuthAuthentication
This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
--
cgit v1.2.3
From eb20b5663e68ce01453eeb855922874001f42d0f Mon Sep 17 00:00:00 2001
From: Rob Romano
Date: Tue, 13 Nov 2012 15:03:42 -0800
Subject: Added documentation on how to use the token authentication login
view.
---
docs/api-guide/authentication.md | 15 +++++++++++++++
1 file changed, 15 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index cb1e2645..a55059a8 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -112,6 +112,21 @@ If you've already created some User`'s, you can run a script like this.
for user in User.objects.all():
Token.objects.get_or_create(user=user)
+When using TokenAuthentication, it may be useful to add a login view for clients to retrieve the token.
+
+REST framework provides a built-in login view. To use it, add a pattern to include the token login view for clients as follows:
+
+ urlpatterns += patterns('',
+ url(r'^api-token-auth/', include('rest_framework.authtoken.urls',
+ namespace='rest_framework'))
+ )
+
+The `r'^api-token-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.
+
+The authtoken login view will render a JSON response when a valid `username` and `password` fields are POST'ed to the view using forms or JSON:
+
+ { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
+
## OAuthAuthentication
This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
--
cgit v1.2.3
From 321ba156ca45da8a4b3328c4aec6a9235f32e5f8 Mon Sep 17 00:00:00 2001
From: Rob Romano
Date: Tue, 13 Nov 2012 16:49:13 -0800
Subject: Renamed AuthTokenView to ObtainAuthToken, added obtain_auth_token
var, updated tests & docs. Left authtoken.urls in place as example.
---
docs/api-guide/authentication.md | 11 ++++-------
1 file changed, 4 insertions(+), 7 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index a55059a8..a30bd22c 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -114,18 +114,15 @@ If you've already created some User`'s, you can run a script like this.
When using TokenAuthentication, it may be useful to add a login view for clients to retrieve the token.
-REST framework provides a built-in login view. To use it, add a pattern to include the token login view for clients as follows:
+REST framework provides a built-in login view for clients to retrieve the token called `rest_framework.authtoken.obtain_auth_token`. To use it, add a pattern to include the token login view for clients as follows:
urlpatterns += patterns('',
- url(r'^api-token-auth/', include('rest_framework.authtoken.urls',
- namespace='rest_framework'))
+ url(r'^api-token-auth/', 'rest_framework.authtoken.obtain_auth_token')
)
-The `r'^api-token-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.
+The `r'^api-token-auth/'` part of pattern can actually be whatever URL you want to use. The authtoken login view will render a JSON response when a valid `username` and `password` fields are POST'ed to the view using forms or JSON:
-The authtoken login view will render a JSON response when a valid `username` and `password` fields are POST'ed to the view using forms or JSON:
-
- { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
+ { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
## OAuthAuthentication
--
cgit v1.2.3
From 38e94bb8b4e04249b18b9b57ef2ddcb7cfc4efa4 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Thu, 15 Nov 2012 11:15:05 +0100
Subject: added global and per resource on/off switch + updated docs
---
docs/api-guide/generic-views.md | 3 ++-
docs/api-guide/settings.md | 6 ++++++
2 files changed, 8 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 9e5119cb..734a91e9 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -149,7 +149,8 @@ Should be mixed in with [MultipleObjectAPIView].
**Arguments**:
-* `page_size` - Hook to adjust page_size per request.
+* `allow_page_size_param` - Allows you to overwrite the global settings `ALLOW_PAGE_SIZE_PARAM` for a specific view.
+* `page_size_param` - Allows you to customize the page_size parameter. Default is `page_size`.
## CreateModelMixin
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 4f87b30d..2f90369b 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -150,4 +150,10 @@ Default: `'accept'`
Default: `'format'`
+## ALLOW_PAGE_SIZE_PARAM
+
+Allows you to globally pass a page size parameter for an individual request.
+
+Default: `'True'`
+
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From 3ae203a0184d27318a8a828ce322b151ade0340f Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Thu, 15 Nov 2012 12:06:43 +0100
Subject: updated script to just use page_size_kwarg
---
docs/api-guide/generic-views.md | 3 +--
docs/api-guide/settings.md | 8 ++++++--
2 files changed, 7 insertions(+), 4 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 734a91e9..3346c70a 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -149,8 +149,7 @@ Should be mixed in with [MultipleObjectAPIView].
**Arguments**:
-* `allow_page_size_param` - Allows you to overwrite the global settings `ALLOW_PAGE_SIZE_PARAM` for a specific view.
-* `page_size_param` - Allows you to customize the page_size parameter. Default is `page_size`.
+* `page_size_kwarg` - Allows you to overwrite the global settings `PAGE_SIZE_KWARG` for a specific view. You can also turn it off for a specific view by setting it to `None`. Default is `page_size`.
## CreateModelMixin
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 2f90369b..8fce9e4e 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -150,10 +150,14 @@ Default: `'accept'`
Default: `'format'`
-## ALLOW_PAGE_SIZE_PARAM
+## PAGE_SIZE_KWARG
Allows you to globally pass a page size parameter for an individual request.
-Default: `'True'`
+The name of the GET parameter of views which inherit ListModelMixin for requesting data with an individual page size.
+
+If the value if this setting is `None` the passing a page size is turned off by default.
+
+Default: `'page_size'`
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From b4cfb46a56c8f7d9bc4340d5443f3a2d57ba9b58 Mon Sep 17 00:00:00 2001
From: Marko Tibold
Date: Fri, 16 Nov 2012 00:22:08 +0100
Subject: WIP on docs for File- and ImageFileds.
---
docs/api-guide/fields.md | 32 ++++++++++++++++++++++++++++++++
1 file changed, 32 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 0485b158..0b25a6ef 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -165,6 +165,38 @@ A floating point representation.
Corresponds to `django.db.models.fields.FloatField`.
+## FileField
+
+A file representation. Performs Django's standard FileField validation.
+
+Corresponds to `django.forms.fields.FileField`.
+
+### Optional arguments
+
+#### `max_length`
+
+Maximum length for the file name. This value is obtained from the model when used with a ModelSerializer.
+
+Defaults to `None`, meaning validation is skipped.
+
+#### `allow_empty_file`
+
+Determines if empty file uploads are allowed.
+
+Defaults to `False`
+
+## ImageField
+
+An image representation.
+
+Corresponds to `django.forms.fields.ImageField`.
+
+### Optional arguments
+
+Same as FileField.
+
+Requires the `PIL` package.
+
---
# Relational Fields
--
cgit v1.2.3
From c5765641a44ad2fb3b80f63f9a47e0dd7f432c94 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 16 Nov 2012 17:28:08 +0000
Subject: Fix typo
---
docs/api-guide/filtering.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index 14ab9a26..95d9d526 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -71,7 +71,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
by filtering against a `username` query parameter in the URL.
"""
queryset = Purchase.objects.all()
- username = self.request.QUERY_PARAMS.get('username', None):
+ username = self.request.QUERY_PARAMS.get('username', None)
if username is not None:
queryset = queryset.filter(purchaser__username=username)
return queryset
--
cgit v1.2.3
From 2f2bde69e42825ad55318e5a5745ee9655b3f81b Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 16 Nov 2012 20:58:49 +0000
Subject: Docs, tox and travis use django-filter 0.5.4
---
docs/api-guide/filtering.md | 5 ++---
1 file changed, 2 insertions(+), 3 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index 95d9d526..53ea7cbc 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -84,9 +84,9 @@ As well as being able to override the default queryset, REST framework also incl
REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package.
-To use REST framework's default filtering backend, first install `django-filter`.
+To use REST framework's filtering backend, first install `django-filter`.
- pip install -e git+https://github.com/alex/django-filter.git#egg=django-filter
+ pip install django-filter
You must also set the filter backend to `DjangoFilterBackend` in your settings:
@@ -94,7 +94,6 @@ You must also set the filter backend to `DjangoFilterBackend` in your settings:
'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend'
}
-**Note**: The currently supported version of `django-filter` is the `master` branch. A PyPI release is expected to be coming soon.
## Specifying filter fields
--
cgit v1.2.3
From 0076e2f462402dbb7bd7b3a446d2c397e6bf8d81 Mon Sep 17 00:00:00 2001
From: Marko Tibold
Date: Fri, 16 Nov 2012 23:23:34 +0100
Subject: Added brief docs for URLField and SlugField.
---
docs/api-guide/fields.md | 12 ++++++++++++
1 file changed, 12 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 0485b158..5977cae2 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -131,6 +131,18 @@ or `django.db.models.fields.TextField`.
**Signature:** `CharField(max_length=None, min_length=None)`
+## URLField
+
+Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
+
+**Signature:** `CharField(max_length=200, min_length=None)`
+
+## SlugField
+
+Corresponds to `django.db.models.fields.SlugField`.
+
+**Signature:** `CharField(max_length=50, min_length=None)`
+
## ChoiceField
A field that can accept a value out of a limited set of choices.
--
cgit v1.2.3
From f801e5d3050591403de04fde7d18522fabc8fe49 Mon Sep 17 00:00:00 2001
From: Marko Tibold
Date: Fri, 16 Nov 2012 23:44:55 +0100
Subject: Simplified docs a bit for FileField and ImageField. Added note about
MultipartParser only supporting file uploads and Django's default upload
handlers.
---
docs/api-guide/fields.md | 26 +++++++++++---------------
1 file changed, 11 insertions(+), 15 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 0b25a6ef..7f42dc5e 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -171,19 +171,11 @@ A file representation. Performs Django's standard FileField validation.
Corresponds to `django.forms.fields.FileField`.
-### Optional arguments
+**Signature:** `FileField(max_length=None, allow_empty_file=False)`
-#### `max_length`
-
-Maximum length for the file name. This value is obtained from the model when used with a ModelSerializer.
-
-Defaults to `None`, meaning validation is skipped.
-
-#### `allow_empty_file`
-
-Determines if empty file uploads are allowed.
-
-Defaults to `False`
+ - `max_length` designates the maximum length for the file name.
+
+ - `allow_empty_file` designates if empty files are allowed.
## ImageField
@@ -191,11 +183,14 @@ An image representation.
Corresponds to `django.forms.fields.ImageField`.
-### Optional arguments
+Requires the `PIL` package.
-Same as FileField.
+Signature and validation is the same as with `FileField`.
-Requires the `PIL` package.
+---
+
+**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since eg json doesn't support file uploads.
+Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
---
@@ -318,3 +313,4 @@ This field is always read-only.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
[cite]: http://www.python.org/dev/peps/pep-0020/
+[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
--
cgit v1.2.3
From 31f01bd6315f46bf28bb4c9c25a5298785fc4fc6 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 16 Nov 2012 22:45:57 +0000
Subject: Polishing to page size query parameters & more docs
---
docs/api-guide/generic-views.md | 22 ++++++++++++++++++----
docs/api-guide/settings.md | 26 ++++++++++++++++----------
2 files changed, 34 insertions(+), 14 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 3346c70a..33ec89d2 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -123,18 +123,36 @@ Each of the generic views provided is built by combining one of the base views b
Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
+**Attributes**:
+
+* `model` - The model that should be used for this view. Used as a fallback for determining the serializer if `serializer_class` is not set, and as a fallback for determining the queryset if `queryset` is not set. Otherwise not required.
+* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. If unset, this defaults to creating a serializer class using `self.model`, with the `DEFAULT_MODEL_SERIALIZER_CLASS` setting as the base serializer class.
+
## MultipleObjectAPIView
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin].
**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy].
+**Attributes**:
+
+* `queryset` - The queryset that should be used for returning objects from this view. If unset, defaults to the default queryset manager for `self.model`.
+* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`.
+* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`.
+
## SingleObjectAPIView
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin].
**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy].
+**Attributes**:
+
+* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`.
+* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+]
+* `slug_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+]
+* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`.
+
---
# Mixins
@@ -147,10 +165,6 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q
Should be mixed in with [MultipleObjectAPIView].
-**Arguments**:
-
-* `page_size_kwarg` - Allows you to overwrite the global settings `PAGE_SIZE_KWARG` for a specific view. You can also turn it off for a specific view by setting it to `None`. Default is `page_size`.
-
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 8fce9e4e..7884d096 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -96,11 +96,21 @@ Default: `rest_framework.serializers.ModelSerializer`
Default: `rest_framework.pagination.PaginationSerializer`
-## FORMAT_SUFFIX_KWARG
+## FILTER_BACKEND
-**TODO**
+The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled.
-Default: `'format'`
+## PAGINATE_BY
+
+The default page size to use for pagination. If set to `None`, pagination is disabled by default.
+
+Default: `None`
+
+## PAGINATE_BY_KWARG
+
+The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to `None`, clients may not override the default page size.
+
+Default: `None`
## UNAUTHENTICATED_USER
@@ -150,14 +160,10 @@ Default: `'accept'`
Default: `'format'`
-## PAGE_SIZE_KWARG
-
-Allows you to globally pass a page size parameter for an individual request.
-
-The name of the GET parameter of views which inherit ListModelMixin for requesting data with an individual page size.
+## FORMAT_SUFFIX_KWARG
-If the value if this setting is `None` the passing a page size is turned off by default.
+**TODO**
-Default: `'page_size'`
+Default: `'format'`
[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From 0eba278e1391604086dab1dfa1bd6ea86fea282e Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 16 Nov 2012 23:22:23 +0000
Subject: Improve pagination docs
---
docs/api-guide/pagination.md | 28 +++++++++++++++++++++-------
1 file changed, 21 insertions(+), 7 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 597baba4..39e6a32d 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -80,23 +80,21 @@ We could now use our pagination serializer in a view like this.
## Pagination in the generic views
-The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, or by turning pagination off completely.
+The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.
-The default pagination style may be set globally, using the `PAGINATION_SERIALIZER` and `PAGINATE_BY` settings. For example.
+The default pagination style may be set globally, using the `DEFAULT_PAGINATION_SERIALIZER_CLASS`, `PAGINATE_BY` and `PAGINATE_BY_PARAM` settings. For example.
REST_FRAMEWORK = {
- 'PAGINATION_SERIALIZER': (
- 'example_app.pagination.CustomPaginationSerializer',
- ),
- 'PAGINATE_BY': 10
+ 'PAGINATE_BY': 10,
+ 'PAGINATE_BY_PARAM': 'page_size'
}
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
class PaginatedListView(ListAPIView):
model = ExampleModel
- pagination_serializer_class = CustomPaginationSerializer
paginate_by = 10
+ paginate_by_param = 'page_size'
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
@@ -122,4 +120,20 @@ For example, to nest a pair of links labelled 'prev' and 'next', and set the nam
results_field = 'objects'
+## Using your custom pagination serializer
+
+To have your custom pagination serializer be used by default use the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting:
+
+ REST_FRAMEWORK = {
+ 'DEFAULT_PAGINATION_SERIALIZER_CLASS':
+ 'example_app.pagination.CustomPaginationSerializer',
+ }
+
+Alternatively, to set your custom pagination serializer on a per-view basis, use the `pagination_serializer_class` attribute on a generic class based view:
+
+ class PaginatedListView(ListAPIView):
+ model = ExampleModel
+ pagination_serializer_class = CustomPaginationSerializer
+ paginate_by = 10
+
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
--
cgit v1.2.3
From 2263ed8b9409c709f6dbad2157f8debffb16c1d8 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 16 Nov 2012 23:24:36 +0000
Subject: Tweak
---
docs/api-guide/pagination.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 39e6a32d..5a35ed75 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -122,7 +122,7 @@ For example, to nest a pair of links labelled 'prev' and 'next', and set the nam
## Using your custom pagination serializer
-To have your custom pagination serializer be used by default use the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting:
+To have your custom pagination serializer be used by default, use the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_SERIALIZER_CLASS':
--
cgit v1.2.3
From f131e533edf58dc8ba7b712b4c3486a3ab053ffc Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 18 Nov 2012 17:57:02 +0000
Subject: Docs, docs, docs, docs, docs, docs
---
docs/api-guide/generic-views.md | 18 ++++++++++++++++++
docs/api-guide/pagination.md | 5 +++--
2 files changed, 21 insertions(+), 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 33ec89d2..428323b8 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -163,30 +163,48 @@ The mixin classes provide the actions that are used to provide the basic view be
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
+If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.
+
+If the queryset is empty this returns a `200 OK` reponse, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`.
+
Should be mixed in with [MultipleObjectAPIView].
## CreateModelMixin
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
+If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value.
+
+If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
+
Should be mixed in with any [GenericAPIView].
## RetrieveModelMixin
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
+If an object can be retrieve this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
+
Should be mixed in with [SingleObjectAPIView].
## UpdateModelMixin
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
+If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response.
+
+If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response.
+
+If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response.
+
Should be mixed in with [SingleObjectAPIView].
## DestroyModelMixin
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
+If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`.
+
Should be mixed in with [SingleObjectAPIView].
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 5a35ed75..ab335e6e 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -70,11 +70,12 @@ We could now use our pagination serializer in a view like this.
# If page is not an integer, deliver first page.
users = paginator.page(1)
except EmptyPage:
- # If page is out of range (e.g. 9999), deliver last page of results.
+ # If page is out of range (e.g. 9999),
+ # deliver last page of results.
users = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
- serializer = PaginatedUserSerializer(instance=users,
+ serializer = PaginatedUserSerializer(users,
context=serializer_context)
return Response(serializer.data)
--
cgit v1.2.3
From de5b071d677074ab3b6b33a843c4b05ba2052a6b Mon Sep 17 00:00:00 2001
From: Jamie Matthews
Date: Mon, 19 Nov 2012 17:22:17 +0000
Subject: Add SerializerMethodField
---
docs/api-guide/fields.md | 6 ++++++
1 file changed, 6 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index d1c31ecc..b19c324a 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -324,5 +324,11 @@ This field is always read-only.
* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
+# Other Fields
+
+## SerializerMethodField
+
+This is a read-only field gets its value by calling a method on the serializer class it's attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object.
+
[cite]: http://www.python.org/dev/peps/pep-0020/
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
--
cgit v1.2.3
From 3ab8c4966d065e930bd6e8bc6c26934ae5c5918c Mon Sep 17 00:00:00 2001
From: Jamie Matthews
Date: Mon, 19 Nov 2012 17:24:08 +0000
Subject: Tweaks to SerializerMethodField docs
---
docs/api-guide/fields.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index b19c324a..ebfb5d47 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -328,7 +328,7 @@ This field is always read-only.
## SerializerMethodField
-This is a read-only field gets its value by calling a method on the serializer class it's attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object.
+This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object.
[cite]: http://www.python.org/dev/peps/pep-0020/
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
--
cgit v1.2.3
From ce5b186ca869b693c945200581ba893123a63ce8 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 19 Nov 2012 21:42:33 +0000
Subject: Docs tweaks.
---
docs/api-guide/authentication.md | 21 ++++++++++++---------
1 file changed, 12 insertions(+), 9 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index a30bd22c..05575f57 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -68,7 +68,7 @@ This policy uses [HTTP Basic Authentication][basicauth], signed against a user's
If successfully authenticated, `BasicAuthentication` provides the following credentials.
-* `request.user` will be a `django.contrib.auth.models.User` instance.
+* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
@@ -92,7 +92,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
If successfully authenticated, `TokenAuthentication` provides the following credentials.
-* `request.user` will be a `django.contrib.auth.models.User` instance.
+* `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
@@ -104,7 +104,7 @@ If you want every user to have an automatically generated Token, you can simply
if created:
Token.objects.create(user=instance)
-If you've already created some User`'s, you can run a script like this.
+If you've already created some User's, you can run a script like this.
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
@@ -112,26 +112,29 @@ If you've already created some User`'s, you can run a script like this.
for user in User.objects.all():
Token.objects.get_or_create(user=user)
-When using TokenAuthentication, it may be useful to add a login view for clients to retrieve the token.
-
-REST framework provides a built-in login view for clients to retrieve the token called `rest_framework.authtoken.obtain_auth_token`. To use it, add a pattern to include the token login view for clients as follows:
+When using TokenAuthentication, you may want to provide a mechanism for clients to obtain a token, given the username and password.
+REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.obtain_auth_token')
)
-The `r'^api-token-auth/'` part of pattern can actually be whatever URL you want to use. The authtoken login view will render a JSON response when a valid `username` and `password` fields are POST'ed to the view using forms or JSON:
+The `r'^api-token-auth/'` part of pattern can actually be whatever URL you want to use.
+
+The `obtain_auth_token` view will render a JSON response when a valid `username` and `password` fields are POST'ed to the view using form data or JSON:
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
+
## SessionAuthentication
@@ -139,7 +142,7 @@ This policy uses Django's default session backend for authentication. Session a
If successfully authenticated, `SessionAuthentication` provides the following credentials.
-* `request.user` will be a `django.contrib.auth.models.User` instance.
+* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
# Custom authentication
--
cgit v1.2.3
From a44a94dd6ea2d9497264e267a0354cb684d398f6 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 19 Nov 2012 22:08:38 +0000
Subject: More docs tweaking.
---
docs/api-guide/authentication.md | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 05575f57..8ed6ef31 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -104,7 +104,7 @@ If you want every user to have an automatically generated Token, you can simply
if created:
Token.objects.create(user=instance)
-If you've already created some User's, you can run a script like this.
+If you've already created some users, you can generate tokens for all existing users like this:
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
@@ -112,16 +112,16 @@ If you've already created some User's, you can run a script like this.
for user in User.objects.all():
Token.objects.get_or_create(user=user)
-When using TokenAuthentication, you may want to provide a mechanism for clients to obtain a token, given the username and password.
+When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password.
REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
urlpatterns += patterns('',
url(r'^api-token-auth/', 'rest_framework.authtoken.obtain_auth_token')
)
-The `r'^api-token-auth/'` part of pattern can actually be whatever URL you want to use.
+Note that the URL part of the pattern can be whatever you want to use.
-The `obtain_auth_token` view will render a JSON response when a valid `username` and `password` fields are POST'ed to the view using form data or JSON:
+The `obtain_auth_token` view will return a JSON response when valid `username` and `password` fields are POSTed to the view using form data or JSON:
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
--
cgit v1.2.3
From 5f4c385a86b877217c1e1bc2eaff58206eabb747 Mon Sep 17 00:00:00 2001
From: Jamie Matthews
Date: Tue, 20 Nov 2012 13:25:21 +0000
Subject: Add example use of SerializerMethodField to docs
---
docs/api-guide/fields.md | 16 +++++++++++++++-
1 file changed, 15 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index ebfb5d47..914d0861 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -328,7 +328,21 @@ This field is always read-only.
## SerializerMethodField
-This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object.
+This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
+
+ from rest_framework import serializers
+ from django.contrib.auth.models import User
+ from django.utils.timezone import now
+
+ class UserSerializer(serializers.ModelSerializer):
+
+ days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
[cite]: http://www.python.org/dev/peps/pep-0020/
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
--
cgit v1.2.3
From 86484668f689864aa54e127a8107bdee55240cea Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 20 Nov 2012 15:38:50 +0100
Subject: added RegexField
---
docs/api-guide/fields.md | 10 ++++++++++
1 file changed, 10 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 0485b158..cb30a52e 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -141,6 +141,16 @@ A text representation, validates the text to be a valid e-mail address.
Corresponds to `django.db.models.fields.EmailField`
+## RegexField
+
+A text representation, that validates the given value matches against a certain regular expression.
+
+Uses Django's `django.core.validators.RegexValidator` for validation.
+
+Corresponds to `django.forms.fields.RegexField`
+
+**Signature:** `RegexField(regex, max_length=None, min_length=None)`
+
## DateField
A date representation.
--
cgit v1.2.3
From 3b43d41e918b70e5ce83f7da2caabcae2e1bcd72 Mon Sep 17 00:00:00 2001
From: Mark Aaron Shirley
Date: Tue, 20 Nov 2012 15:57:54 -0800
Subject: Documentation changes for partial serializer updates
---
docs/api-guide/serializers.md | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index a9589144..624c4159 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -77,6 +77,10 @@ When deserializing data, we can either create a new instance, or update an exist
serializer = CommentSerializer(data=data) # Create new instance
serializer = CommentSerializer(comment, data=data) # Update `instance`
+By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the `partial` argument in order to allow partial updates.
+
+ serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `instance` with partial data
+
## Validation
When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages.
--
cgit v1.2.3
From 9459289d7d388074045b726225cb6e140f3c18c3 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Wed, 21 Nov 2012 13:35:20 +0100
Subject: updated comparison due to pep8 programming recommendations
http://www.python.org/dev/peps/pep-0008/#programming-recommendations
---
docs/api-guide/serializers.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index a9589144..048c1200 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -34,7 +34,7 @@ Declaring a serializer looks very similar to declaring a form:
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
- if instance:
+ if instance is not None:
instance.title = attrs['title']
instance.content = attrs['content']
instance.created = attrs['created']
--
cgit v1.2.3
From e8a41322fbf96866c70ceb6b188894e02e7718f4 Mon Sep 17 00:00:00 2001
From: Yuri Prezument
Date: Tue, 27 Nov 2012 11:23:40 +0200
Subject: api-guide/views.md - add imports to code example
* It wasn't clear where `Response` should be imported from.
---
docs/api-guide/views.md | 3 +++
1 file changed, 3 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 5b072827..6cef1cd0 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -19,6 +19,9 @@ Using the `APIView` class is pretty much the same as using a regular `View` clas
For example:
+ from rest_framework.views import APIView, Response
+ from rest_framework import authentication, permissions
+
class ListUsers(APIView):
"""
View to list all users in the system.
--
cgit v1.2.3
From 80be571b2e1deebff247ce5dfc4a325f2e2df9ae Mon Sep 17 00:00:00 2001
From: Yuri Prezument
Date: Tue, 27 Nov 2012 19:42:37 +0200
Subject: Import from correct place
---
docs/api-guide/views.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 6cef1cd0..d1e42ec1 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -19,7 +19,8 @@ Using the `APIView` class is pretty much the same as using a regular `View` clas
For example:
- from rest_framework.views import APIView, Response
+ from rest_framework.views import APIView
+ from rest_framework.response import Response
from rest_framework import authentication, permissions
class ListUsers(APIView):
--
cgit v1.2.3
From fd383b2b5e752962242066b3587deec5820eaa2e Mon Sep 17 00:00:00 2001
From: Pavel Savchenko
Date: Wed, 28 Nov 2012 11:58:34 +0200
Subject: Fix location of obtain_auth_token view
---
docs/api-guide/authentication.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 8ed6ef31..43fc15d2 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -116,7 +116,7 @@ When using `TokenAuthentication`, you may want to provide a mechanism for client
REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
urlpatterns += patterns('',
- url(r'^api-token-auth/', 'rest_framework.authtoken.obtain_auth_token')
+ url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
)
Note that the URL part of the pattern can be whatever you want to use.
--
cgit v1.2.3
From 3868241f6acda96fbd08cc81211b09ffbc2f38b3 Mon Sep 17 00:00:00 2001
From: Marko Tibold
Date: Wed, 5 Dec 2012 15:09:06 +0100
Subject: Update docs/api-guide/permissions.md
@permission_classes takes a tuple or list.---
docs/api-guide/permissions.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index 1a746fb6..fce68f6d 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -53,7 +53,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi
Or, if you're using the `@api_view` decorator with function based views.
@api_view('GET')
- @permission_classes(IsAuthenticated)
+ @permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
content = {
'status': 'request was permitted'
--
cgit v1.2.3
From ff01ae3571298b9da67f9b9583f0cb264676ed2b Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Dec 2012 13:01:03 +0000
Subject: Version 2.1.8
---
docs/api-guide/fields.md | 3 +++
1 file changed, 3 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 1d4c34cb..50a09701 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -293,6 +293,7 @@ By default these fields are read-write, although you can change this behaviour u
**Arguments**:
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
## SlugRelatedField / ManySlugRelatedField
@@ -304,6 +305,7 @@ By default these fields read-write, although you can change this behaviour using
* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
@@ -319,6 +321,7 @@ By default, `HyperlinkedRelatedField` is read-write, although you can change thi
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
+* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
## HyperLinkedIdentityField
--
cgit v1.2.3
From e198a2b37673a07a7cc374175c205362da34360e Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Thu, 13 Dec 2012 16:57:17 +0100
Subject: added RetrieveUpdateAPIView
---
docs/api-guide/generic-views.md | 8 ++++++++
1 file changed, 8 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 428323b8..ef09dfe5 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -97,6 +97,14 @@ Provides `get` and `post` method handlers.
Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin]
+## RetrieveUpdateAPIView
+
+Used for **read or update** endpoints to represent a **single model instance**.
+
+Provides `get` and `put` method handlers.
+
+Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin]
+
## RetrieveDestroyAPIView
Used for **read or delete** endpoints to represent a **single model instance**.
--
cgit v1.2.3
From 5f9ecd1c7ad2f52ad5711d2a89bb1884f5b662f9 Mon Sep 17 00:00:00 2001
From: Reinout van Rees
Date: Fri, 21 Dec 2012 10:42:40 +0100
Subject: slug_kwarg attribute doesn't work; it should be slug_url_kwarg
---
docs/api-guide/generic-views.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 428323b8..27c7d3f6 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -7,11 +7,11 @@
>
> — [Django Documentation][cite]
-One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
+One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
-If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
+If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
## Examples
@@ -29,7 +29,7 @@ For more complex cases you might also want to override various methods on the vi
model = User
serializer_class = UserSerializer
permission_classes = (IsAdminUser,)
-
+
def get_paginate_by(self, queryset):
"""
Use smaller pagination for HTML representations.
@@ -150,14 +150,14 @@ Provides a base view for acting on a single object, by combining REST framework'
* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`.
* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+]
-* `slug_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+]
+* `slug_url_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+]
* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`.
---
# Mixins
-The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour.
+The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour.
## ListModelMixin
@@ -220,4 +220,4 @@ Should be mixed in with [SingleObjectAPIView].
[CreateModelMixin]: #createmodelmixin
[RetrieveModelMixin]: #retrievemodelmixin
[UpdateModelMixin]: #updatemodelmixin
-[DestroyModelMixin]: #destroymodelmixin
\ No newline at end of file
+[DestroyModelMixin]: #destroymodelmixin
--
cgit v1.2.3
From 5d4ea3d23fdb173b4109a64b2d4231d93d394387 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 28 Dec 2012 12:59:24 +0000
Subject: Add .validate() example
---
docs/api-guide/serializers.md | 17 ++++++++++++++++-
1 file changed, 16 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 19efde3c..da1efb8f 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -110,7 +110,22 @@ Your `validate_` methods should either just return the `attrs` dictio
### Object-level validation
-To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`.
+To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example:
+
+ from rest_framework import serializers
+
+ class EventSerializer(serializers.Serializer):
+ description = serializers.CahrField(max_length=100)
+ start = serializers.DateTimeField()
+ finish = serializers.DateTimeField()
+
+ def validate(self, attrs):
+ """
+ Check that the start is before the stop.
+ """
+ if attrs['start'] < attrs['finish']:
+ raise serializers.ValidationError("finish must occur after start")
+ return attrs
## Saving object state
--
cgit v1.2.3
From 1f6af163fece28db3ba7943edce2415a23874d44 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 29 Dec 2012 12:15:15 +0000
Subject: Tweak quote
---
docs/api-guide/serializers.md | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index da1efb8f..d98a602f 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -4,8 +4,7 @@
> Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
-will take some serious design work. Any offers to help out in this
-area would be gratefully accepted.
+will take some serious design work.
>
> — Russell Keith-Magee, [Django users group][cite]
--
cgit v1.2.3
From 8fad0a727a897970531a087346ecd44f361b25f4 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 31 Dec 2012 08:53:40 +0000
Subject: Relation fields move into relations.py
---
docs/api-guide/fields.md | 179 +++++++-------------------------------------
docs/api-guide/relations.md | 139 ++++++++++++++++++++++++++++++++++
2 files changed, 166 insertions(+), 152 deletions(-)
create mode 100644 docs/api-guide/relations.md
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
index 50a09701..5bc8f7f7 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -2,11 +2,11 @@
# Serializer fields
-> Flat is better than nested.
+> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it -- normalizing it to a consistent format.
>
-> — [The Zen of Python][cite]
+> — [Django documentation][cite]
-Serializer fields handle converting between primative values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
+Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
---
@@ -28,7 +28,7 @@ Defaults to the name of the field.
### `read_only`
-Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization.
+Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance during deserialization.
Defaults to `False`
@@ -41,7 +41,7 @@ Defaults to `True`.
### `default`
-If set, this gives the default value that will be used for the field if none is supplied. If not set the default behaviour is to not populate the attribute at all.
+If set, this gives the default value that will be used for the field if none is supplied. If not set the default behavior is to not populate the attribute at all.
### `validators`
@@ -96,9 +96,9 @@ Would produce output similar to:
'expired': True
}
-By default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when necessary.
+By default, the `Field` class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
-You can customize this behaviour by overriding the `.to_native(self, value)` method.
+You can customize this behavior by overriding the `.to_native(self, value)` method.
## WritableField
@@ -110,6 +110,24 @@ A generic field that can be tied to any arbitrary model field. The `ModelField`
**Signature:** `ModelField(model_field=)`
+## SerializerMethodField
+
+This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
+
+ from rest_framework import serializers
+ from django.contrib.auth.models import User
+ from django.utils.timezone import now
+
+ class UserSerializer(serializers.ModelSerializer):
+
+ days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
+
---
# Typed Fields
@@ -211,151 +229,8 @@ Signature and validation is the same as with `FileField`.
---
-**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since eg json doesn't support file uploads.
+**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
----
-
-# Relational Fields
-
-Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
-
-## RelatedField
-
-This field can be applied to any of the following:
-
-* A `ForeignKey` field.
-* A `OneToOneField` field.
-* A reverse OneToOne relationship
-* Any other "to-one" relationship.
-
-By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
-
-You can customise this behaviour by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
-
-## ManyRelatedField
-
-This field can be applied to any of the following:
-
-* A `ManyToManyField` field.
-* A reverse ManyToMany relationship.
-* A reverse ForeignKey relationship
-* Any other "to-many" relationship.
-
-By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
-
-For example, given the following models:
-
- class TaggedItem(models.Model):
- """
- Tags arbitrary model instances using a generic relation.
-
- See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
- """
- tag = models.SlugField()
- content_type = models.ForeignKey(ContentType)
- object_id = models.PositiveIntegerField()
- content_object = GenericForeignKey('content_type', 'object_id')
-
- def __unicode__(self):
- return self.tag
-
-
- class Bookmark(models.Model):
- """
- A bookmark consists of a URL, and 0 or more descriptive tags.
- """
- url = models.URLField()
- tags = GenericRelation(TaggedItem)
-
-And a model serializer defined like this:
-
- class BookmarkSerializer(serializers.ModelSerializer):
- tags = serializers.ManyRelatedField(source='tags')
-
- class Meta:
- model = Bookmark
- exclude = ('id',)
-
-Then an example output format for a Bookmark instance would be:
-
- {
- 'tags': [u'django', u'python'],
- 'url': u'https://www.djangoproject.com/'
- }
-
-## PrimaryKeyRelatedField / ManyPrimaryKeyRelatedField
-
-`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
-
-By default these fields are read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
-* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
-
-## SlugRelatedField / ManySlugRelatedField
-
-`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
-
-By default these fields read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
-* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
-
-## HyperlinkedRelatedField / ManyHyperlinkedRelatedField
-
-`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
-
-By default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
-
-**Arguments**:
-
-* `view_name` - The view name that should be used as the target of the relationship. **required**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
-* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
-* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
-* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
-* `null` - If set to `True`, the field will accept values of `None` or the emptystring for nullable relationships.
-
-## HyperLinkedIdentityField
-
-This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
-
-This field is always read-only.
-
-**Arguments**:
-
-* `view_name` - The view name that should be used as the target of the relationship. **required**.
-* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
-* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
-* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
-* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
-
-# Other Fields
-
-## SerializerMethodField
-
-This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
-
- from rest_framework import serializers
- from django.contrib.auth.models import User
- from django.utils.timezone import now
-
- class UserSerializer(serializers.ModelSerializer):
-
- days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
-
- class Meta:
- model = User
-
- def get_days_since_joined(self, obj):
- return (now() - obj.date_joined).days
-
-[cite]: http://www.python.org/dev/peps/pep-0020/
+[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
new file mode 100644
index 00000000..351b5e09
--- /dev/null
+++ b/docs/api-guide/relations.md
@@ -0,0 +1,139 @@
+
+
+# Serializer relations
+
+> Bad programmers worry about the code.
+> Good programmers worry about data structures and their relationships.
+>
+> — [Linus Torvalds][cite]
+
+
+Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
+
+---
+
+**Note:** The relational fields are declared in `relations.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`.
+
+---
+
+## RelatedField
+
+This field can be applied to any of the following:
+
+* A `ForeignKey` field.
+* A `OneToOneField` field.
+* A reverse OneToOne relationship
+* Any other "to-one" relationship.
+
+By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
+
+You can customize this behavior by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
+
+## ManyRelatedField
+
+This field can be applied to any of the following:
+
+* A `ManyToManyField` field.
+* A reverse ManyToMany relationship.
+* A reverse ForeignKey relationship
+* Any other "to-many" relationship.
+
+By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
+
+For example, given the following models:
+
+ class TaggedItem(models.Model):
+ """
+ Tags arbitrary model instances using a generic relation.
+
+ See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
+ """
+ tag = models.SlugField()
+ content_type = models.ForeignKey(ContentType)
+ object_id = models.PositiveIntegerField()
+ content_object = GenericForeignKey('content_type', 'object_id')
+
+ def __unicode__(self):
+ return self.tag
+
+
+ class Bookmark(models.Model):
+ """
+ A bookmark consists of a URL, and 0 or more descriptive tags.
+ """
+ url = models.URLField()
+ tags = GenericRelation(TaggedItem)
+
+And a model serializer defined like this:
+
+ class BookmarkSerializer(serializers.ModelSerializer):
+ tags = serializers.ManyRelatedField(source='tags')
+
+ class Meta:
+ model = Bookmark
+ exclude = ('id',)
+
+Then an example output format for a Bookmark instance would be:
+
+ {
+ 'tags': [u'django', u'python'],
+ 'url': u'https://www.djangoproject.com/'
+ }
+
+## PrimaryKeyRelatedField
+## ManyPrimaryKeyRelatedField
+
+`PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField` will represent the target of the relationship using it's primary key.
+
+By default these fields are read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
+
+## SlugRelatedField
+## ManySlugRelatedField
+
+`SlugRelatedField` and `ManySlugRelatedField` will represent the target of the relationship using a unique slug.
+
+By default these fields read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`.
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
+
+## HyperlinkedRelatedField
+## ManyHyperlinkedRelatedField
+
+`HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField` will represent the target of the relationship using a hyperlink.
+
+By default, `HyperlinkedRelatedField` is read-write, although you can change this behavior using the `read_only` flag.
+
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
+* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
+* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
+* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
+
+## HyperLinkedIdentityField
+
+This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
+
+This field is always read-only.
+
+**Arguments**:
+
+* `view_name` - The view name that should be used as the target of the relationship. **required**.
+* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
+* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
+* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
+* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
+
+[cite]: http://lwn.net/Articles/193245/
--
cgit v1.2.3
From d9df15f32174f9ddac7135ee33c74771a3173350 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 7 Jan 2013 14:56:26 +0000
Subject: Added @juanriaza's `djangorestframework-msgpack` package to the docs.
---
docs/api-guide/parsers.md | 13 +++++++++++++
docs/api-guide/renderers.md | 14 +++++++++++++-
2 files changed, 26 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 185b616c..9356b420 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -159,4 +159,17 @@ For example:
files = {name: uploaded}
return DataAndFiles(data, files)
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## MessagePack
+
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
+
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
+[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[juanriaza]: https://github.com/juanriaza
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
\ No newline at end of file
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 374ff0ab..389dec1f 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -271,6 +271,15 @@ Exceptions raised and handled by an HTML renderer will attempt to render using o
Templates will render with a `RequestContext` which includes the `status_code` and `details` keys.
+---
+
+# Third party packages
+
+The following third party packages are also available.
+
+## MessagePack
+
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md
@@ -280,4 +289,7 @@ Templates will render with a `RequestContext` which includes the `status_code` a
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
[application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
-[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
\ No newline at end of file
+[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
+[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[juanriaza]: https://github.com/juanriaza
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
\ No newline at end of file
--
cgit v1.2.3
From e429f702e00ed807d68e90cd6a6af2749eb0b73e Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 7 Jan 2013 20:17:52 +0000
Subject: Fix PAGINATE_BY_PARAM docs. Refs #551
---
docs/api-guide/settings.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 7884d096..8c87f2ca 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -106,7 +106,7 @@ The default page size to use for pagination. If set to `None`, pagination is di
Default: `None`
-## PAGINATE_BY_KWARG
+## PAGINATE_BY_PARAM
The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to `None`, clients may not override the default page size.
--
cgit v1.2.3
From 31b585f26a8fc72e5b527b7672c7691e374dc494 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 7 Jan 2013 21:13:10 +0000
Subject: Note paginate_by=None usage. Fixes #555.
---
docs/api-guide/pagination.md | 2 ++
1 file changed, 2 insertions(+)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index ab335e6e..71253afb 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -97,6 +97,8 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie
paginate_by = 10
paginate_by_param = 'page_size'
+Note that using a `paginate_by` value of `None` will turn off pagination for the view.
+
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
---
--
cgit v1.2.3
From 4df1172665f6df3d4c4df53b4836e2c6ed462da5 Mon Sep 17 00:00:00 2001
From: Marc Tamlyn
Date: Tue, 8 Jan 2013 11:45:55 +0000
Subject: Fix reference to BasicAuthentication in settings.
---
docs/api-guide/settings.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 8c87f2ca..a422e5f6 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -65,7 +65,7 @@ Default:
(
'rest_framework.authentication.SessionAuthentication',
- 'rest_framework.authentication.UserBasicAuthentication'
+ 'rest_framework.authentication.BasicAuthentication'
)
## DEFAULT_PERMISSION_CLASSES
--
cgit v1.2.3
From cb235977f654ce6c385cf5245cfa086c2ed54780 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 9 Jan 2013 09:22:17 +0000
Subject: Include CSRF note in SessionAuthentication docs.
---
docs/api-guide/authentication.md | 14 +++-----------
1 file changed, 3 insertions(+), 11 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 43fc15d2..c089e4e1 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -125,17 +125,6 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
-
-
## SessionAuthentication
This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
@@ -145,6 +134,8 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
* `request.user` will be a Django `User` instance.
* `request.auth` will be `None`.
+If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
+
# Custom authentication
To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
@@ -154,3 +145,4 @@ To implement a custom authentication policy, subclass `BaseAuthentication` and o
[oauth]: http://oauth.net/2/
[permission]: permissions.md
[throttling]: throttling.md
+[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
--
cgit v1.2.3
From 919c5e1e01106918af9f26c506c2198fbf731923 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Fri, 11 Jan 2013 20:26:44 +0100
Subject: Fix typo in permission_classes
---
docs/api-guide/authentication.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index c089e4e1..afd9a261 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -52,7 +52,7 @@ Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication))
- @permissions_classes((IsAuthenticated,))
+ @permission_classes((IsAuthenticated,))
def example_view(request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
--
cgit v1.2.3
From a7e7c441a4e4eb058c0b879e62d976b848b618c6 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 14 Jan 2013 17:38:32 +0000
Subject: Add link to @mjumbewu's CSV package
---
docs/api-guide/renderers.md | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 389dec1f..86bbdaa1 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -280,6 +280,9 @@ The following third party packages are also available.
## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
+## CSV
+
+Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md
@@ -292,4 +295,5 @@ The following third party packages are also available.
[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
[juanriaza]: https://github.com/juanriaza
-[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
\ No newline at end of file
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack[mjumbewu]: https://github.com/mjumbewu
+[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
\ No newline at end of file
--
cgit v1.2.3
From 190473f5089c5862e610bd823d6b67257ab1376f Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 14 Jan 2013 17:38:45 +0000
Subject: Tweak messagepack links
---
docs/api-guide/parsers.md | 2 +-
docs/api-guide/renderers.md | 8 +++++---
2 files changed, 6 insertions(+), 4 deletions(-)
(limited to 'docs/api-guide')
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 9356b420..de968557 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -167,7 +167,7 @@ The following third party packages are also available.
## MessagePack
-[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 86bbdaa1..b4f7ec3d 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -279,7 +279,8 @@ The following third party packages are also available.
## MessagePack
-[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack].
+[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
+
## CSV
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
@@ -293,7 +294,8 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
-[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[messagepack]: http://msgpack.org/
[juanriaza]: https://github.com/juanriaza
-[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack[mjumbewu]: https://github.com/mjumbewu
+[mjumbewu]: https://github.com/mjumbewu
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
\ No newline at end of file
--
cgit v1.2.3