@@ -16,13 +16,48 @@ Serializer fields handle converting between primative values and internal dataty
...
@@ -16,13 +16,48 @@ Serializer fields handle converting between primative values and internal dataty
# Generic Fields
# Generic Fields
These generic fields are used for representing arbitrary model fields or the output of model methods.
## Field
## Field
A generic, read-only field. You can use this field for any attribute that does not need to support write operations.
A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations.
For example, using the following model.
class Account(models.Model):
owner = models.ForeignKey('auth.user')
name = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
payment_expiry = models.DateTimeField()
def has_expired(self):
now = datetime.datetime.now()
return now > self.payment_expiry
A serializer definition that looked like this:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
expired = Field(source='has_expired')
class Meta:
fields = ('url', 'owner', 'name', 'expired')
Would produced output similar to:
{
'url': 'http://example.com/api/accounts/3/',
'owner': 'http://example.com/api/users/12/',
'name': 'FooCorp business account',
'expired': True
}
Be 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 neccesary.
You can customize this behaviour by overriding the `.to_native(self, value)` method.
## WritableField
## WritableField
A field that supports both read and
A field that supports both read and write operations. By itself `WriteableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
## ModelField
## ModelField
...
@@ -56,10 +91,86 @@ These fields represent basic datatypes, and support both reading and writing val
...
@@ -56,10 +91,86 @@ These fields represent basic datatypes, and support both reading and writing val
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`.
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.
@@ -88,20 +88,12 @@ If your API includes views that can serve both regular webpages and API response
...
@@ -88,20 +88,12 @@ If your API includes views that can serve both regular webpages and API response
**.format:**`'.xml'`
**.format:**`'.xml'`
## DocumentingHTMLRenderer
## HTMLRenderer
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.
**.media_type:**`text/html`
**.format:**`'.api'`
## HTMLTemplateRenderer
Renders data to HTML, using Django's standard template rendering.
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`.
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 HTMLTemplateRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
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 template name is determined by (in order of preference):
The template name is determined by (in order of preference):
...
@@ -109,18 +101,54 @@ The template name is determined by (in order of preference):
...
@@ -109,18 +101,54 @@ The template name is determined by (in order of preference):
2. An explicit `.template_name` attribute set on this class.
2. An explicit `.template_name` attribute set on this class.
3. The return result of calling `view.get_template_names()`.
3. The return result of calling `view.get_template_names()`.
You can use `HTMLTemplateRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
An example of a view that uses `HTMLRenderer`:
If you're building websites that use `HTMLTemplateRenderer` along with other renderer classes, you should consider listing `HTMLTemplateRenderer` 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.
class UserInstance(generics.RetrieveUserAPIView):
"""
A view that returns a templated HTML representations of a given user.
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.
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.
**.media_type:**`text/html`
**.media_type:**`text/html`
**.format:**`'.html'`
**.format:**`'.html'`
## 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.
**.media_type:**`text/html`
**.format:**`'.api'`
## Custom renderers
## Custom renderers
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type)` method.
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type)` method.
For example:
from django.utils.encoding import smart_unicode
from rest_framework import renderers
class PlainText(renderers.BaseRenderer):
media_type = 'text/plain'
format = 'txt'
def render(self, data, media_type):
if isinstance(data, basestring):
return data
return smart_unicode(data)
---
---
# Advanced renderer usage
# Advanced renderer usage
...
@@ -139,7 +167,7 @@ In some cases you might want your view to use different serialization styles dep
...
@@ -139,7 +167,7 @@ In some cases you might want your view to use different serialization styles dep
*`status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes].
*`status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes].
*`template_name`: A template name to use if `HTMLTemplateRenderer` is selected.
*`template_name`: A template name to use if `HTMLRenderer` is selected.
*`headers`: A dictionary of HTTP headers to use in the response.
*`headers`: A dictionary of HTTP headers to use in the response.
## .render()
## .render()
...
@@ -68,7 +68,7 @@ The rendered content of the response. The `.render()` method must have been cal
...
@@ -68,7 +68,7 @@ The rendered content of the response. The `.render()` method must have been cal
## .template_name
## .template_name
The `template_name`, if supplied. Only required if `HTMLTemplateRenderer` or some other custom template renderer is the accepted renderer for the reponse.
The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the reponse.
## .accepted_renderer
## .accepted_renderer
...
@@ -84,4 +84,4 @@ Set automatically by the `APIView` or `@api_view` immediately before the respons
...
@@ -84,4 +84,4 @@ Set automatically by the `APIView` or `@api_view` immediately before the respons