From 714a90d7559885c15e5b2c86ef6f457fdf857ee0 Mon Sep 17 00:00:00 2001
From: Sébastien Piquemal
Date: Tue, 24 Jan 2012 21:21:10 +0200
Subject: documentation for request module
---
docs/library/request.rst | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 docs/library/request.rst
(limited to 'docs')
diff --git a/docs/library/request.rst b/docs/library/request.rst
new file mode 100644
index 00000000..5e99826a
--- /dev/null
+++ b/docs/library/request.rst
@@ -0,0 +1,5 @@
+:mod:`request`
+=====================
+
+.. automodule:: request
+ :members:
--
cgit v1.2.3
From 152c385f4de37558fe4e522abad5b97f0cf7ddce Mon Sep 17 00:00:00 2001
From: Sébastien Piquemal
Date: Wed, 25 Jan 2012 00:11:54 +0200
Subject: enhanced request how-to + example
---
docs/howto/requestmixin.rst | 76 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 76 insertions(+)
create mode 100644 docs/howto/requestmixin.rst
(limited to 'docs')
diff --git a/docs/howto/requestmixin.rst b/docs/howto/requestmixin.rst
new file mode 100644
index 00000000..a00fdad0
--- /dev/null
+++ b/docs/howto/requestmixin.rst
@@ -0,0 +1,76 @@
+Using the enhanced request in all your views
+==============================================
+
+This example shows how you can use Django REST framework's enhanced `request` in your own views, without having to use the full-blown :class:`views.View` class.
+
+What can it do for you ? Mostly, it will take care of parsing the request's content, and handling equally all HTTP methods ...
+
+Before
+--------
+
+In order to support `JSON` or other serial formats, you might have parsed manually the request's content with something like : ::
+
+ class MyView(View):
+
+ def put(self, request, *args, **kwargs):
+ content_type = request.META['CONTENT_TYPE']
+ if (content_type == 'application/json'):
+ raw_data = request.read()
+ parsed_data = json.loads(raw_data)
+
+ # PLUS as many `elif` as formats you wish to support ...
+
+ # then do stuff with your data :
+ self.do_stuff(parsed_data['bla'], parsed_data['hoho'])
+
+ # and finally respond something
+
+... and you were unhappy because this looks hackish.
+
+Also, you might have tried uploading files with a PUT request - *and given up* since that's complicated to achieve even with Django 1.3.
+
+
+After
+------
+
+All the dirty `Content-type` checking and content reading and parsing is done for you, and you only need to do the following : ::
+
+ class MyView(MyBaseViewUsingEnhancedRequest):
+
+ def put(self, request, *args, **kwargs):
+ self.do_stuff(request.DATA['bla'], request.DATA['hoho'])
+ # and finally respond something
+
+So the parsed content is magically available as `.DATA` on the `request` object.
+
+Also, if you uploaded files, they are available as `.FILES`, like with a normal POST request.
+
+.. note:: Note that all the above is also valid for a POST request.
+
+
+How to add it to your custom views ?
+--------------------------------------
+
+Now that you're convinced you need to use the enhanced request object, here is how you can add it to all your custom views : ::
+
+ from django.views.generic.base import View
+
+ from djangorestframework.mixins import RequestMixin
+ from djangorestframework import parsers
+
+
+ class MyBaseViewUsingEnhancedRequest(RequestMixin, View):
+ """
+ Base view enabling the usage of enhanced requests with user defined views.
+ """
+
+ parsers = parsers.DEFAULT_PARSERS
+
+ def dispatch(self, request, *args, **kwargs):
+ self.request = request
+ request = self.get_request()
+ return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs)
+
+And then, use this class as a base for all your custom views.
+
+.. note:: you can also check the request example.
--
cgit v1.2.3
From 6963fd3623ee217fe489abb25f0ffa8c0781e4cd Mon Sep 17 00:00:00 2001
From: Sébastien Piquemal
Date: Tue, 7 Feb 2012 16:22:14 +0200
Subject: some docs for Request/Response/mixins
---
docs/howto/requestmixin.rst | 9 ++++-----
1 file changed, 4 insertions(+), 5 deletions(-)
(limited to 'docs')
diff --git a/docs/howto/requestmixin.rst b/docs/howto/requestmixin.rst
index a00fdad0..c0aadb3f 100644
--- a/docs/howto/requestmixin.rst
+++ b/docs/howto/requestmixin.rst
@@ -1,7 +1,7 @@
Using the enhanced request in all your views
==============================================
-This example shows how you can use Django REST framework's enhanced `request` in your own views, without having to use the full-blown :class:`views.View` class.
+This example shows how you can use Django REST framework's enhanced `request` - :class:`request.Request` - in your own views, without having to use the full-blown :class:`views.View` class.
What can it do for you ? Mostly, it will take care of parsing the request's content, and handling equally all HTTP methods ...
@@ -64,13 +64,12 @@ Now that you're convinced you need to use the enhanced request object, here is h
Base view enabling the usage of enhanced requests with user defined views.
"""
- parsers = parsers.DEFAULT_PARSERS
+ parser_classes = parsers.DEFAULT_PARSERS
def dispatch(self, request, *args, **kwargs):
- self.request = request
- request = self.get_request()
+ request = self.prepare_request(request)
return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs)
And then, use this class as a base for all your custom views.
-.. note:: you can also check the request example.
+.. note:: you can see this live in the examples.
--
cgit v1.2.3
From af9e4f69d732cc643d6ec7ae13d4a19ac0332d44 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 21 Feb 2012 20:12:14 +0000
Subject: Merging master into develop
---
docs/howto/reverse.rst | 47 ++++++++++++++++++++++++++++++++++++
docs/howto/setup.rst | 65 ++++++++++++++++++++++++++++++++------------------
docs/index.rst | 14 +++++++----
docs/library/utils.rst | 5 ++++
4 files changed, 104 insertions(+), 27 deletions(-)
create mode 100644 docs/howto/reverse.rst
create mode 100644 docs/library/utils.rst
(limited to 'docs')
diff --git a/docs/howto/reverse.rst b/docs/howto/reverse.rst
new file mode 100644
index 00000000..e4efbbca
--- /dev/null
+++ b/docs/howto/reverse.rst
@@ -0,0 +1,47 @@
+Returning URIs from your Web APIs
+=================================
+
+ "The central feature that distinguishes the REST architectural style from
+ other network-based styles is its emphasis on a uniform interface between
+ components."
+
+ -- Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures
+
+As a rule, it's probably better practice to return absolute URIs from you web APIs, e.g. "http://example.com/foobar", rather than returning relative URIs, e.g. "/foobar".
+
+The advantages of doing so are:
+
+* It's more explicit.
+* It leaves less work for your API clients.
+* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
+* It allows us to easily do things like markup HTML representations with hyperlinks.
+
+Django REST framework provides two utility functions to make it simpler to return absolute URIs from your Web API.
+
+There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.
+
+reverse(viewname, request, ...)
+-------------------------------
+
+The :py:func:`~utils.reverse` function has the same behavior as :py:func:`django.core.urlresolvers.reverse` [1]_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port::
+
+ from djangorestframework.utils import reverse
+ from djangorestframework.views import View
+
+ class MyView(View):
+ def get(self, request):
+ context = {
+ 'url': reverse('year-summary', request, args=[1945])
+ }
+
+ return Response(context)
+
+reverse_lazy(viewname, request, ...)
+------------------------------------
+
+The :py:func:`~utils.reverse_lazy` function has the same behavior as :py:func:`django.core.urlresolvers.reverse_lazy` [2]_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port.
+
+.. rubric:: Footnotes
+
+.. [1] https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
+.. [2] https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
diff --git a/docs/howto/setup.rst b/docs/howto/setup.rst
index 22f98f0c..0af1449c 100644
--- a/docs/howto/setup.rst
+++ b/docs/howto/setup.rst
@@ -3,45 +3,58 @@
Setup
=====
-Installing into site-packages
------------------------------
+Templates
+---------
-If you need to manually install Django REST framework to your ``site-packages`` directory, run the ``setup.py`` script::
+Django REST framework uses a few templates for the HTML and plain text
+documenting renderers. You'll need to ensure ``TEMPLATE_LOADERS`` setting
+contains ``'django.template.loaders.app_directories.Loader'``.
+This will already be the case by default.
- python setup.py install
+You may customize the templates by creating a new template called
+``djangorestframework/api.html`` in your project, which should extend
+``djangorestframework/base.html`` and override the appropriate
+block tags. For example::
-Template Loaders
-----------------
+ {% extends "djangorestframework/base.html" %}
-Django REST framework uses a few templates for the HTML and plain text documenting renderers.
+ {% block title %}My API{% endblock %}
-* Ensure ``TEMPLATE_LOADERS`` setting contains ``'django.template.loaders.app_directories.Loader'``.
+ {% block branding %}
+
My API
+ {% endblock %}
-This will be the case by default so you shouldn't normally need to do anything here.
-Admin Styling
--------------
+Styling
+-------
-Django REST framework uses the admin media for styling. When running using Django's testserver this is automatically served for you,
-but once you move onto a production server, you'll want to make sure you serve the admin media separately, exactly as you would do
-`if using the Django admin `_.
+Django REST framework requires `django.contrib.staticfiles`_ to serve it's css.
+If you're using Django 1.2 you'll need to use the seperate
+`django-staticfiles`_ package instead.
+
+You can override the styling by creating a file in your top-level static
+directory named ``djangorestframework/css/style.css``
-* Ensure that the ``ADMIN_MEDIA_PREFIX`` is set appropriately and that you are serving the admin media.
- (Django's testserver will automatically serve the admin media for you)
Markdown
--------
-The Python `markdown library `_ is not required but comes recommended.
+`Python markdown`_ is not required but comes recommended.
+
+If markdown is installed your :class:`.Resource` descriptions can include
+`markdown formatting`_ which will be rendered by the self-documenting API.
+
+YAML
+----
+
+YAML support is optional, and requires `PyYAML`_.
-If markdown is installed your :class:`.Resource` descriptions can include `markdown style formatting
-`_ which will be rendered by the HTML documenting renderer.
-login/logout
----------------------------------
+Login / Logout
+--------------
-Django REST framework comes with a few views that can be useful including an api
-login and logout views::
+Django REST framework includes login and logout views that are useful if
+you're using the self-documenting API::
from django.conf.urls.defaults import patterns
@@ -51,3 +64,9 @@ login and logout views::
(r'^accounts/logout/$', 'api_logout'),
)
+.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
+.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
+.. _URLObject: http://pypi.python.org/pypi/URLObject/
+.. _Python markdown: http://www.freewisdom.org/projects/python-markdown/
+.. _markdown formatting: http://daringfireball.net/projects/markdown/syntax
+.. _PyYAML: http://pypi.python.org/pypi/PyYAML
\ No newline at end of file
diff --git a/docs/index.rst b/docs/index.rst
index ecc1f118..b969c4a3 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -40,8 +40,11 @@ Requirements
------------
* Python (2.5, 2.6, 2.7 supported)
-* Django (1.2, 1.3, 1.4-alpha supported)
-
+* Django (1.2, 1.3, 1.4 supported)
+* `django.contrib.staticfiles`_ (or `django-staticfiles`_ for Django 1.2)
+* `URLObject`_ >= 2.0.0
+* `Markdown`_ >= 2.1.0 (Optional)
+* `PyYAML`_ >= 3.10 (Optional)
Installation
------------
@@ -54,8 +57,6 @@ Or get the latest development version using git::
git clone git@github.com:tomchristie/django-rest-framework.git
-Or you can `download the current release `_.
-
Setup
-----
@@ -114,3 +115,8 @@ Indices and tables
* :ref:`modindex`
* :ref:`search`
+.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
+.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
+.. _URLObject: http://pypi.python.org/pypi/URLObject/
+.. _Markdown: http://pypi.python.org/pypi/Markdown/
+.. _PyYAML: http://pypi.python.org/pypi/PyYAML
diff --git a/docs/library/utils.rst b/docs/library/utils.rst
new file mode 100644
index 00000000..653f24fd
--- /dev/null
+++ b/docs/library/utils.rst
@@ -0,0 +1,5 @@
+:mod:`utils`
+==============
+
+.. automodule:: utils
+ :members:
--
cgit v1.2.3
From 5fd4c639d7c64572dd07dc31dcd627bed9469b05 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 21 Feb 2012 20:57:36 +0000
Subject: Merge master into develop
---
docs/howto/reverse.rst | 18 +++++-------------
docs/library/reverse.rst | 5 +++++
2 files changed, 10 insertions(+), 13 deletions(-)
create mode 100644 docs/library/reverse.rst
(limited to 'docs')
diff --git a/docs/howto/reverse.rst b/docs/howto/reverse.rst
index e4efbbca..73b8fa4d 100644
--- a/docs/howto/reverse.rst
+++ b/docs/howto/reverse.rst
@@ -1,12 +1,6 @@
Returning URIs from your Web APIs
=================================
- "The central feature that distinguishes the REST architectural style from
- other network-based styles is its emphasis on a uniform interface between
- components."
-
- -- Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures
-
As a rule, it's probably better practice to return absolute URIs from you web APIs, e.g. "http://example.com/foobar", rather than returning relative URIs, e.g. "/foobar".
The advantages of doing so are:
@@ -23,9 +17,9 @@ There's no requirement for you to use them, but if you do then the self-describi
reverse(viewname, request, ...)
-------------------------------
-The :py:func:`~utils.reverse` function has the same behavior as :py:func:`django.core.urlresolvers.reverse` [1]_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port::
+The :py:func:`~reverse.reverse` function has the same behavior as `django.core.urlresolvers.reverse`_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port::
- from djangorestframework.utils import reverse
+ from djangorestframework.reverse import reverse
from djangorestframework.views import View
class MyView(View):
@@ -39,9 +33,7 @@ The :py:func:`~utils.reverse` function has the same behavior as :py:func:`django
reverse_lazy(viewname, request, ...)
------------------------------------
-The :py:func:`~utils.reverse_lazy` function has the same behavior as :py:func:`django.core.urlresolvers.reverse_lazy` [2]_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port.
-
-.. rubric:: Footnotes
+The :py:func:`~reverse.reverse_lazy` function has the same behavior as `django.core.urlresolvers.reverse_lazy`_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port.
-.. [1] https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
-.. [2] https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
+.. _django.core.urlresolvers.reverse: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
+.. _django.core.urlresolvers.reverse_lazy: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
diff --git a/docs/library/reverse.rst b/docs/library/reverse.rst
new file mode 100644
index 00000000..a2c29c48
--- /dev/null
+++ b/docs/library/reverse.rst
@@ -0,0 +1,5 @@
+:mod:`reverse`
+================
+
+.. automodule:: reverse
+ :members:
--
cgit v1.2.3
From 1cde31c86d9423e9b7a7409c2ef2ba7c0500e47f Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 25 Feb 2012 18:45:17 +0000
Subject: Massive merge
---
docs/howto/setup.rst | 18 +++++++++---------
docs/index.rst | 6 ++++++
2 files changed, 15 insertions(+), 9 deletions(-)
(limited to 'docs')
diff --git a/docs/howto/setup.rst b/docs/howto/setup.rst
index 0af1449c..081c6412 100644
--- a/docs/howto/setup.rst
+++ b/docs/howto/setup.rst
@@ -49,20 +49,20 @@ YAML
YAML support is optional, and requires `PyYAML`_.
-
Login / Logout
--------------
-Django REST framework includes login and logout views that are useful if
-you're using the self-documenting API::
+Django REST framework includes login and logout views that are needed if
+you're using the self-documenting API.
+
+Make sure you include the following in your `urlconf`::
- from django.conf.urls.defaults import patterns
+ from django.conf.urls.defaults import patterns, url
- urlpatterns = patterns('djangorestframework.views',
- # Add your resources here
- (r'^accounts/login/$', 'api_login'),
- (r'^accounts/logout/$', 'api_logout'),
- )
+ urlpatterns = patterns('',
+ ...
+ url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework'))
+ )
.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
diff --git a/docs/index.rst b/docs/index.rst
index b969c4a3..a6745fca 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -64,6 +64,12 @@ To add Django REST framework to a Django project:
* Ensure that the ``djangorestframework`` directory is on your ``PYTHONPATH``.
* Add ``djangorestframework`` to your ``INSTALLED_APPS``.
+* Add the following to your URLconf. (To include the REST framework Login/Logout views.)::
+
+ urlpatterns = patterns('',
+ ...
+ url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework'))
+ )
For more information on settings take a look at the :ref:`setup` section.
--
cgit v1.2.3
From 578017e01d1da4746ae0045268043cfd74d41b42 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 29 Aug 2012 20:57:37 +0100
Subject: New docs
---
docs/check_sphinx.py | 9 -
docs/conf.py | 228 --------------------
docs/contents.rst | 10 -
docs/csrf.md | 4 +
docs/examples.rst | 23 --
docs/examples/blogpost.rst | 37 ----
docs/examples/modelviews.rst | 56 -----
docs/examples/objectstore.rst | 17 --
docs/examples/permissions.rst | 66 ------
docs/examples/pygments.rst | 89 --------
docs/examples/sandbox.rst | 12 --
docs/examples/views.rst | 56 -----
docs/formoverloading.md | 46 ++++
docs/howto.rst | 8 -
docs/howto/alternativeframeworks.rst | 35 ---
docs/howto/mixin.rst | 30 ---
docs/howto/requestmixin.rst | 75 -------
docs/howto/reverse.rst | 39 ----
docs/howto/setup.rst | 73 -------
docs/howto/usingcurl.rst | 30 ---
docs/howto/usingurllib2.rst | 39 ----
docs/index.md | 62 ++++++
docs/index.rst | 128 -----------
docs/library.rst | 8 -
docs/library/authentication.rst | 5 -
docs/library/compat.rst | 5 -
docs/library/mixins.rst | 5 -
docs/library/parsers.rst | 5 -
docs/library/permissions.rst | 5 -
docs/library/renderers.rst | 10 -
docs/library/request.rst | 5 -
docs/library/resource.rst | 5 -
docs/library/response.rst | 5 -
docs/library/reverse.rst | 5 -
docs/library/serializer.rst | 5 -
docs/library/status.rst | 5 -
docs/library/utils.rst | 5 -
docs/library/views.rst | 5 -
docs/parsers.md | 5 +
docs/renderers.md | 6 +
docs/request.md | 76 +++++++
docs/requirements.txt | 8 -
docs/response.md | 27 +++
docs/serializers.md | 47 ++++
docs/status.md | 17 ++
docs/templates/layout.html | 28 ---
docs/tutorial/1-serialization.md | 236 +++++++++++++++++++++
docs/tutorial/2-requests-and-responses.md | 137 ++++++++++++
docs/tutorial/3-class-based-views.md | 137 ++++++++++++
.../4-authentication-permissions-and-throttling.md | 3 +
.../5-relationships-and-hyperlinked-apis.md | 9 +
docs/tutorial/6-resource-orientated-projects.md | 49 +++++
docs/urls.md | 42 ++++
docs/views.md | 43 ++++
54 files changed, 946 insertions(+), 1179 deletions(-)
delete mode 100644 docs/check_sphinx.py
delete mode 100644 docs/conf.py
delete mode 100644 docs/contents.rst
create mode 100644 docs/csrf.md
delete mode 100644 docs/examples.rst
delete mode 100644 docs/examples/blogpost.rst
delete mode 100644 docs/examples/modelviews.rst
delete mode 100644 docs/examples/objectstore.rst
delete mode 100644 docs/examples/permissions.rst
delete mode 100644 docs/examples/pygments.rst
delete mode 100644 docs/examples/sandbox.rst
delete mode 100644 docs/examples/views.rst
create mode 100644 docs/formoverloading.md
delete mode 100644 docs/howto.rst
delete mode 100644 docs/howto/alternativeframeworks.rst
delete mode 100644 docs/howto/mixin.rst
delete mode 100644 docs/howto/requestmixin.rst
delete mode 100644 docs/howto/reverse.rst
delete mode 100644 docs/howto/setup.rst
delete mode 100644 docs/howto/usingcurl.rst
delete mode 100644 docs/howto/usingurllib2.rst
create mode 100644 docs/index.md
delete mode 100644 docs/index.rst
delete mode 100644 docs/library.rst
delete mode 100644 docs/library/authentication.rst
delete mode 100644 docs/library/compat.rst
delete mode 100644 docs/library/mixins.rst
delete mode 100644 docs/library/parsers.rst
delete mode 100644 docs/library/permissions.rst
delete mode 100644 docs/library/renderers.rst
delete mode 100644 docs/library/request.rst
delete mode 100644 docs/library/resource.rst
delete mode 100644 docs/library/response.rst
delete mode 100644 docs/library/reverse.rst
delete mode 100644 docs/library/serializer.rst
delete mode 100644 docs/library/status.rst
delete mode 100644 docs/library/utils.rst
delete mode 100644 docs/library/views.rst
create mode 100644 docs/parsers.md
create mode 100644 docs/renderers.md
create mode 100644 docs/request.md
delete mode 100644 docs/requirements.txt
create mode 100644 docs/response.md
create mode 100644 docs/serializers.md
create mode 100644 docs/status.md
delete mode 100644 docs/templates/layout.html
create mode 100644 docs/tutorial/1-serialization.md
create mode 100644 docs/tutorial/2-requests-and-responses.md
create mode 100644 docs/tutorial/3-class-based-views.md
create mode 100644 docs/tutorial/4-authentication-permissions-and-throttling.md
create mode 100644 docs/tutorial/5-relationships-and-hyperlinked-apis.md
create mode 100644 docs/tutorial/6-resource-orientated-projects.md
create mode 100644 docs/urls.md
create mode 100644 docs/views.md
(limited to 'docs')
diff --git a/docs/check_sphinx.py b/docs/check_sphinx.py
deleted file mode 100644
index feb04abd..00000000
--- a/docs/check_sphinx.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import pytest
-import subprocess
-
-def test_build_docs(tmpdir):
- doctrees = tmpdir.join("doctrees")
- htmldir = "html" #we want to keep the docs
- subprocess.check_call([
- "sphinx-build", "-q", "-bhtml",
- "-d", str(doctrees), ".", str(htmldir)])
diff --git a/docs/conf.py b/docs/conf.py
deleted file mode 100644
index 16388814..00000000
--- a/docs/conf.py
+++ /dev/null
@@ -1,228 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# Asset Platform documentation build configuration file, created by
-# sphinx-quickstart on Fri Nov 19 20:24:09 2010.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
-
-import sys, os
-
-sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
-sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'djangorestframework')) # for documenting the library
-sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'examples')) # for importing settings
-import settings
-from django.core.management import setup_environ
-setup_environ(settings)
-
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.insert(0, os.path.abspath('.'))
-
-# -- General configuration -----------------------------------------------------
-
-# If your documentation needs a minimal Sphinx version, state it here.
-#needs_sphinx = '1.0'
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
-
-# Add any paths that contain templates here, relative to this directory.
-templates_path = ['templates']
-
-# The suffix of source filenames.
-source_suffix = '.rst'
-
-# The encoding of source files.
-#source_encoding = 'utf-8-sig'
-
-# The master toctree document.
-master_doc = 'index'
-
-# General information about the project.
-project = u'django-rest-framework'
-copyright = u'2011, Tom Christie'
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
-
-import djangorestframework
-
-version = djangorestframework.__version__
-
-# The full version, including alpha/beta/rc tags.
-release = version
-
-autodoc_member_order='bysource'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of patterns, relative to source directory, that match files and
-# directories to ignore when looking for source files.
-exclude_patterns = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages. See the documentation for
-# a list of builtin themes.
-html_theme = 'sphinxdoc'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further. For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents. If None, it defaults to
-# " v documentation".
-html_title = "Django REST framework"
-
-# A shorter title for the navigation bar. Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-#html_logo = None
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = []
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
-# If false, no module index is generated.
-#html_domain_indices = True
-
-# If false, no index is generated.
-#html_use_index = True
-
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
-
-# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
-#html_show_sphinx = True
-
-# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
-#html_show_copyright = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a tag referring to it. The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# This is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = None
-
-# Output file base name for HTML help builder.
-#htmlhelp_basename = ''
-
-
-# -- Options for LaTeX output --------------------------------------------------
-
-# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
-#latex_documents = [
-# (),
-#]
-
-# The name of an image file (relative to this directory) to place at the top of
-# the title page.
-#latex_logo = None
-
-# For "manual" documents, if this is true, then toplevel headings are parts,
-# not chapters.
-#latex_use_parts = False
-
-# If true, show page references after internal links.
-#latex_show_pagerefs = False
-
-# If true, show URL addresses after external links.
-#latex_show_urls = False
-
-# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_domain_indices = True
-
-# -- Options for manual page output --------------------------------------------
-
-# One entry per manual page. List of tuples
-# (source start file, name, description, authors, manual section).
-#man_pages = [
-# ()
-#]
-
-linkcheck_timeout = 120 # seconds, set to extra large value for link_checks
diff --git a/docs/contents.rst b/docs/contents.rst
deleted file mode 100644
index d8e6e742..00000000
--- a/docs/contents.rst
+++ /dev/null
@@ -1,10 +0,0 @@
-Documentation
-=============
-
-.. toctree::
- :maxdepth: 2
-
- howto
- library
- examples
-
diff --git a/docs/csrf.md b/docs/csrf.md
new file mode 100644
index 00000000..8e0b9480
--- /dev/null
+++ b/docs/csrf.md
@@ -0,0 +1,4 @@
+REST framework and CSRF protection
+==================================
+
+> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability -- very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." - Jeff Atwood
\ No newline at end of file
diff --git a/docs/examples.rst b/docs/examples.rst
deleted file mode 100644
index 64088345..00000000
--- a/docs/examples.rst
+++ /dev/null
@@ -1,23 +0,0 @@
-Examples
-========
-
-There are a few real world web API examples included with Django REST framework.
-
-#. :doc:`examples/objectstore` - Using :class:`views.View` classes for APIs that do not map to models.
-#. :doc:`examples/pygments` - Using :class:`views.View` classes with forms for input validation.
-#. :doc:`examples/blogpost` - Using :class:`views.ModelView` classes for APIs that map directly to models.
-
-All the examples are freely available for testing in the sandbox:
-
- http://rest.ep.io
-
-(The :doc:`examples/sandbox` resource is also documented.)
-
-Example Reference
------------------
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- examples/*
diff --git a/docs/examples/blogpost.rst b/docs/examples/blogpost.rst
deleted file mode 100644
index 11e376ef..00000000
--- a/docs/examples/blogpost.rst
+++ /dev/null
@@ -1,37 +0,0 @@
-Blog Posts API
-==============
-
-* http://rest.ep.io/blog-post/
-
-The models
-----------
-
-In this example we're working from two related models:
-
-``models.py``
-
-.. include:: ../../examples/blogpost/models.py
- :literal:
-
-Creating the resources
-----------------------
-
-We need to create two resources that we map to our two existing models, in order to describe how the models should be serialized.
-Our resource descriptions will typically go into a module called something like 'resources.py'
-
-``resources.py``
-
-.. include:: ../../examples/blogpost/resources.py
- :literal:
-
-Creating views for our resources
---------------------------------
-
-Once we've created the resources there's very little we need to do to create the API.
-For each resource we'll create a base view, and an instance view.
-The generic views :class:`.ListOrCreateModelView` and :class:`.InstanceModelView` provide default operations for listing, creating and updating our models via the API, and also automatically provide input validation using default ModelForms for each model.
-
-``urls.py``
-
-.. include:: ../../examples/blogpost/urls.py
- :literal:
diff --git a/docs/examples/modelviews.rst b/docs/examples/modelviews.rst
deleted file mode 100644
index b67d50d9..00000000
--- a/docs/examples/modelviews.rst
+++ /dev/null
@@ -1,56 +0,0 @@
-Getting Started - Model Views
------------------------------
-
-.. note::
-
- A live sandbox instance of this API is available:
-
- http://rest.ep.io/model-resource-example/
-
- You can browse the API using a web browser, or from the command line::
-
- curl -X GET http://rest.ep.io/resource-example/ -H 'Accept: text/plain'
-
-Often you'll want parts of your API to directly map to existing django models. Django REST framework handles this nicely for you in a couple of ways:
-
-#. It automatically provides suitable create/read/update/delete methods for your views.
-#. Input validation occurs automatically, by using appropriate `ModelForms `_.
-
-Here's the model we're working from in this example:
-
-``models.py``
-
-.. include:: ../../examples/modelresourceexample/models.py
- :literal:
-
-To add an API for the model, first we need to create a Resource for the model.
-
-``resources.py``
-
-.. include:: ../../examples/modelresourceexample/resources.py
- :literal:
-
-Then we simply map a couple of views to the Resource in our urlconf.
-
-``urls.py``
-
-.. include:: ../../examples/modelresourceexample/urls.py
- :literal:
-
-And we're done. We've now got a fully browseable API, which supports multiple input and output media types, and has all the nice automatic field validation that Django gives us for free.
-
-We can visit the API in our browser:
-
-* http://rest.ep.io/model-resource-example/
-
-Or access it from the command line using curl:
-
-.. code-block:: bash
-
- # Demonstrates API's input validation using form input
- bash: curl -X POST --data 'foo=true' http://rest.ep.io/model-resource-example/
- {"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
-
- # Demonstrates API's input validation using JSON input
- bash: curl -X POST -H 'Content-Type: application/json' --data-binary '{"foo":true}' http://rest.ep.io/model-resource-example/
- {"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
diff --git a/docs/examples/objectstore.rst b/docs/examples/objectstore.rst
deleted file mode 100644
index 0939fe9c..00000000
--- a/docs/examples/objectstore.rst
+++ /dev/null
@@ -1,17 +0,0 @@
-Object Store API
-================
-
-* http://rest.ep.io/object-store/
-
-This example shows an object store API that can be used to store arbitrary serializable content.
-
-``urls.py``
-
-.. include:: ../../examples/objectstore/urls.py
- :literal:
-
-``views.py``
-
-.. include:: ../../examples/objectstore/views.py
- :literal:
-
diff --git a/docs/examples/permissions.rst b/docs/examples/permissions.rst
deleted file mode 100644
index eafc3255..00000000
--- a/docs/examples/permissions.rst
+++ /dev/null
@@ -1,66 +0,0 @@
-Permissions
-===========
-
-This example will show how you can protect your api by using authentication
-and how you can limit the amount of requests a user can do to a resource by setting
-a throttle to your view.
-
-Authentication
---------------
-
-If you want to protect your api from unauthorized users, Django REST Framework
-offers you two default authentication methods:
-
- * Basic Authentication
- * Django's session-based authentication
-
-These authentication methods are by default enabled. But they are not used unless
-you specifically state that your view requires authentication.
-
-To do this you just need to import the `Isauthenticated` class from the frameworks' `permissions` module.::
-
- from djangorestframework.permissions import IsAuthenticated
-
-Then you enable authentication by setting the right 'permission requirement' to the `permissions` class attribute of your View like
-the example View below.:
-
-
-.. literalinclude:: ../../examples/permissionsexample/views.py
- :pyobject: LoggedInExampleView
-
-The `IsAuthenticated` permission will only let a user do a 'GET' if he is authenticated. Try it
-yourself on the live sandbox__
-
-__ http://rest.ep.io/permissions-example/loggedin
-
-
-Throttling
-----------
-
-If you want to limit the amount of requests a client is allowed to do on
-a resource, then you can set a 'throttle' to achieve this.
-
-For this to work you'll need to import the `PerUserThrottling` class from the `permissions`
-module.::
-
- from djangorestframework.permissions import PerUserThrottling
-
-In the example below we have limited the amount of requests one 'client' or 'user'
-may do on our view to 10 requests per minute.:
-
-.. literalinclude:: ../../examples/permissionsexample/views.py
- :pyobject: ThrottlingExampleView
-
-Try it yourself on the live sandbox__.
-
-__ http://rest.ep.io/permissions-example/throttling
-
-Now if you want a view to require both aurhentication and throttling, you simply declare them
-both::
-
- permissions = (PerUserThrottling, Isauthenticated)
-
-To see what other throttles are available, have a look at the :mod:`permissions` module.
-
-If you want to implement your own authentication method, then refer to the :mod:`authentication`
-module.
diff --git a/docs/examples/pygments.rst b/docs/examples/pygments.rst
deleted file mode 100644
index 4e72f754..00000000
--- a/docs/examples/pygments.rst
+++ /dev/null
@@ -1,89 +0,0 @@
-Code Highlighting API
-=====================
-
-This example demonstrates creating a REST API using a :class:`.Resource` with some form validation on the input.
-We're going to provide a simple wrapper around the awesome `pygments `_ library, to create the Web API for a simple pastebin.
-
-.. note::
-
- A live sandbox instance of this API is available at http://rest.ep.io/pygments/
-
- You can browse the API using a web browser, or from the command line::
-
- curl -X GET http://rest.ep.io/pygments/ -H 'Accept: text/plain'
-
-
-URL configuration
------------------
-
-We'll need two resources:
-
-* A resource which represents the root of the API.
-* A resource which represents an instance of a highlighted snippet.
-
-``urls.py``
-
-.. include:: ../../examples/pygments_api/urls.py
- :literal:
-
-Form validation
----------------
-
-We'll now add a form to specify what input fields are required when creating a new highlighted code snippet. This will include:
-
-* The code text itself.
-* An optional title for the code.
-* A flag to determine if line numbers should be included.
-* Which programming language to interpret the code snippet as.
-* Which output style to use for the highlighting.
-
-``forms.py``
-
-.. include:: ../../examples/pygments_api/forms.py
- :literal:
-
-Creating the resources
-----------------------
-
-We'll need to define 3 resource handling methods on our resources.
-
-* ``PygmentsRoot.get()`` method, which lists all the existing snippets.
-* ``PygmentsRoot.post()`` method, which creates new snippets.
-* ``PygmentsInstance.get()`` method, which returns existing snippets.
-
-And set a number of attributes on our resources.
-
-* Set the ``allowed_methods`` and ``anon_allowed_methods`` attributes on both resources allowing for full unauthenticated access.
-* Set the ``form`` attribute on the ``PygmentsRoot`` resource, to give us input validation when we create snippets.
-* Set the ``emitters`` attribute on the ``PygmentsInstance`` resource, so that
-
-``views.py``
-
-.. include:: ../../examples/pygments_api/views.py
- :literal:
-
-Completed
----------
-
-And we're done. We now have an API that is:
-
-* **Browseable.** The API supports media types for both programmatic and human access, and can be accessed either via a browser or from the command line.
-* **Self describing.** The API serves as it's own documentation.
-* **Well connected.** The API can be accessed fully by traversal from the initial URL. Clients never need to construct URLs themselves.
-
-Our API also supports multiple media types for both input and output, and applies sensible input validation in all cases.
-
-For example if we make a POST request using form input:
-
-.. code-block:: bash
-
- bash: curl -X POST --data 'code=print "hello, world!"' --data 'style=foobar' -H 'X-Requested-With: XMLHttpRequest' http://rest.ep.io/pygments/
- {"detail": {"style": ["Select a valid choice. foobar is not one of the available choices."], "lexer": ["This field is required."]}}
-
-Or if we make the same request using JSON:
-
-.. code-block:: bash
-
- bash: curl -X POST --data-binary '{"code":"print \"hello, world!\"", "style":"foobar"}' -H 'Content-Type: application/json' -H 'X-Requested-With: XMLHttpRequest' http://rest.ep.io/pygments/
- {"detail": {"style": ["Select a valid choice. foobar is not one of the available choices."], "lexer": ["This field is required."]}}
-
diff --git a/docs/examples/sandbox.rst b/docs/examples/sandbox.rst
deleted file mode 100644
index ec465aaf..00000000
--- a/docs/examples/sandbox.rst
+++ /dev/null
@@ -1,12 +0,0 @@
-Sandbox Root API
-================
-
-The Resource
-------------
-
-The root level resource of the Django REST framework examples is a simple read only resource:
-
-``view.py``
-
-.. include:: ../../examples/sandbox/views.py
- :literal:
diff --git a/docs/examples/views.rst b/docs/examples/views.rst
deleted file mode 100644
index db0db0d7..00000000
--- a/docs/examples/views.rst
+++ /dev/null
@@ -1,56 +0,0 @@
-Getting Started - Views
------------------------
-
-.. note::
-
- A live sandbox instance of this API is available:
-
- http://rest.ep.io/resource-example/
-
- You can browse the API using a web browser, or from the command line::
-
- curl -X GET http://rest.ep.io/resource-example/ -H 'Accept: text/plain'
-
-We're going to start off with a simple example, that demonstrates a few things:
-
-#. Creating views.
-#. Linking views.
-#. Writing method handlers on views.
-#. Adding form validation to views.
-
-First we'll define two views in our urlconf.
-
-``urls.py``
-
-.. include:: ../../examples/resourceexample/urls.py
- :literal:
-
-Now we'll add a form that we'll use for input validation. This is completely optional, but it's often useful.
-
-``forms.py``
-
-.. include:: ../../examples/resourceexample/forms.py
- :literal:
-
-Now we'll write our views. The first is a read only view that links to three instances of the second. The second view just has some stub handler methods to help us see that our example is working.
-
-``views.py``
-
-.. include:: ../../examples/resourceexample/views.py
- :literal:
-
-That's us done. Our API now provides both programmatic access using JSON and XML, as well a nice browseable HTML view, so we can now access it both from the browser:
-
-* http://rest.ep.io/resource-example/
-
-And from the command line:
-
-.. code-block:: bash
-
- # Demonstrates API's input validation using form input
- bash: curl -X POST --data 'foo=true' http://rest.ep.io/resource-example/1/
- {"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
-
- # Demonstrates API's input validation using JSON input
- bash: curl -X POST -H 'Content-Type: application/json' --data-binary '{"foo":true}' http://rest.ep.io/resource-example/1/
- {"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
diff --git a/docs/formoverloading.md b/docs/formoverloading.md
new file mode 100644
index 00000000..cab47db9
--- /dev/null
+++ b/docs/formoverloading.md
@@ -0,0 +1,46 @@
+Supporting browser-based PUT & DELETE
+=====================================
+
+> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE" - [RESTful Web Services](1), Leonard Richardson & Sam Ruby.
+
+This is the same strategy as is used in [Ruby on Rails](2).
+
+Overloading the HTTP method
+---------------------------
+
+For example, given the following form:
+
+
+
+`request.method` would return `"DELETE"`.
+
+Overloading the HTTP content type
+---------------------------------
+
+Browser-based submission of content types other than form are supported by using form fields named `_content` and `_content_type`:
+
+For example, given the following form:
+
+
+
+`request.content_type` would return `"application/json"`, and `request.content` would return `"{'count': 1}"`
+
+Why not just use Javascript?
+============================
+
+**[TODO]**
+
+Doesn't HTML5 support PUT and DELETE forms?
+===========================================
+
+Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec](3). There remains [ongoing discussion](4) about adding support for `PUT` and `DELETE`, as well as how to support content-types other than form-encoded data.
+
+[1]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
+[2]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
+[3]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
+[4]: http://amundsen.com/examples/put-delete-forms/
diff --git a/docs/howto.rst b/docs/howto.rst
deleted file mode 100644
index 8fdc0926..00000000
--- a/docs/howto.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-How Tos, FAQs & Notes
-=====================
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- howto/*
diff --git a/docs/howto/alternativeframeworks.rst b/docs/howto/alternativeframeworks.rst
deleted file mode 100644
index dc8d1ea6..00000000
--- a/docs/howto/alternativeframeworks.rst
+++ /dev/null
@@ -1,35 +0,0 @@
-Alternative frameworks & Why Django REST framework
-==================================================
-
-Alternative frameworks
-----------------------
-
-There are a number of alternative REST frameworks for Django:
-
-* `django-piston `_ is very mature, and has a large community behind it. This project was originally based on piston code in parts.
-* `django-tasypie `_ is also very good, and has a very active and helpful developer community and maintainers.
-* Other interesting projects include `dagny `_ and `dj-webmachine `_
-
-
-Why use Django REST framework?
-------------------------------
-
-The big benefits of using Django REST framework come down to:
-
-1. It's based on Django's class based views, which makes it simple, modular, and future-proof.
-2. It stays as close as possible to Django idioms and language throughout.
-3. The browse-able API makes working with the APIs extremely quick and easy.
-
-
-Why was this project created?
------------------------------
-
-For me the browse-able API is the most important aspect of Django REST framework.
-
-I wanted to show that Web APIs could easily be made Web browse-able,
-and demonstrate how much better browse-able Web APIs are to work with.
-
-Being able to navigate and use a Web API directly in the browser is a huge win over only having command line and programmatic
-access to the API. It enables the API to be properly self-describing, and it makes it much much quicker and easier to work with.
-There's no fundamental reason why the Web APIs we're creating shouldn't be able to render to HTML as well as JSON/XML/whatever,
-and I really think that more Web API frameworks *in whatever language* ought to be taking a similar approach.
diff --git a/docs/howto/mixin.rst b/docs/howto/mixin.rst
deleted file mode 100644
index 1a84f2ad..00000000
--- a/docs/howto/mixin.rst
+++ /dev/null
@@ -1,30 +0,0 @@
-Using Django REST framework Mixin classes
-=========================================
-
-This example demonstrates creating a REST API **without** using Django REST framework's :class:`.Resource` or :class:`.ModelResource`, but instead using Django's :class:`View` class, and adding the :class:`ResponseMixin` class to provide full HTTP Accept header content negotiation,
-a browseable Web API, and much of the other goodness that Django REST framework gives you for free.
-
-.. note::
-
- A live sandbox instance of this API is available for testing:
-
- * http://rest.ep.io/mixin/
-
- You can browse the API using a web browser, or from the command line::
-
- curl -X GET http://rest.ep.io/mixin/
-
-
-URL configuration
------------------
-
-Everything we need for this example can go straight into the URL conf...
-
-``urls.py``
-
-.. include:: ../../examples/mixin/urls.py
- :literal:
-
-That's it. Auto-magically our API now supports multiple output formats, specified either by using
-standard HTTP Accept header content negotiation, or by using the `&_accept=application/json` style parameter overrides.
-We even get a nice HTML view which can be used to self-document our API.
diff --git a/docs/howto/requestmixin.rst b/docs/howto/requestmixin.rst
deleted file mode 100644
index c0aadb3f..00000000
--- a/docs/howto/requestmixin.rst
+++ /dev/null
@@ -1,75 +0,0 @@
-Using the enhanced request in all your views
-==============================================
-
-This example shows how you can use Django REST framework's enhanced `request` - :class:`request.Request` - in your own views, without having to use the full-blown :class:`views.View` class.
-
-What can it do for you ? Mostly, it will take care of parsing the request's content, and handling equally all HTTP methods ...
-
-Before
---------
-
-In order to support `JSON` or other serial formats, you might have parsed manually the request's content with something like : ::
-
- class MyView(View):
-
- def put(self, request, *args, **kwargs):
- content_type = request.META['CONTENT_TYPE']
- if (content_type == 'application/json'):
- raw_data = request.read()
- parsed_data = json.loads(raw_data)
-
- # PLUS as many `elif` as formats you wish to support ...
-
- # then do stuff with your data :
- self.do_stuff(parsed_data['bla'], parsed_data['hoho'])
-
- # and finally respond something
-
-... and you were unhappy because this looks hackish.
-
-Also, you might have tried uploading files with a PUT request - *and given up* since that's complicated to achieve even with Django 1.3.
-
-
-After
-------
-
-All the dirty `Content-type` checking and content reading and parsing is done for you, and you only need to do the following : ::
-
- class MyView(MyBaseViewUsingEnhancedRequest):
-
- def put(self, request, *args, **kwargs):
- self.do_stuff(request.DATA['bla'], request.DATA['hoho'])
- # and finally respond something
-
-So the parsed content is magically available as `.DATA` on the `request` object.
-
-Also, if you uploaded files, they are available as `.FILES`, like with a normal POST request.
-
-.. note:: Note that all the above is also valid for a POST request.
-
-
-How to add it to your custom views ?
---------------------------------------
-
-Now that you're convinced you need to use the enhanced request object, here is how you can add it to all your custom views : ::
-
- from django.views.generic.base import View
-
- from djangorestframework.mixins import RequestMixin
- from djangorestframework import parsers
-
-
- class MyBaseViewUsingEnhancedRequest(RequestMixin, View):
- """
- Base view enabling the usage of enhanced requests with user defined views.
- """
-
- parser_classes = parsers.DEFAULT_PARSERS
-
- def dispatch(self, request, *args, **kwargs):
- request = self.prepare_request(request)
- return super(MyBaseViewUsingEnhancedRequest, self).dispatch(request, *args, **kwargs)
-
-And then, use this class as a base for all your custom views.
-
-.. note:: you can see this live in the examples.
diff --git a/docs/howto/reverse.rst b/docs/howto/reverse.rst
deleted file mode 100644
index 73b8fa4d..00000000
--- a/docs/howto/reverse.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-Returning URIs from your Web APIs
-=================================
-
-As a rule, it's probably better practice to return absolute URIs from you web APIs, e.g. "http://example.com/foobar", rather than returning relative URIs, e.g. "/foobar".
-
-The advantages of doing so are:
-
-* It's more explicit.
-* It leaves less work for your API clients.
-* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
-* It allows us to easily do things like markup HTML representations with hyperlinks.
-
-Django REST framework provides two utility functions to make it simpler to return absolute URIs from your Web API.
-
-There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier.
-
-reverse(viewname, request, ...)
--------------------------------
-
-The :py:func:`~reverse.reverse` function has the same behavior as `django.core.urlresolvers.reverse`_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port::
-
- from djangorestframework.reverse import reverse
- from djangorestframework.views import View
-
- class MyView(View):
- def get(self, request):
- context = {
- 'url': reverse('year-summary', request, args=[1945])
- }
-
- return Response(context)
-
-reverse_lazy(viewname, request, ...)
-------------------------------------
-
-The :py:func:`~reverse.reverse_lazy` function has the same behavior as `django.core.urlresolvers.reverse_lazy`_, except that it takes a request object and returns a fully qualified URL, using the request to determine the host and port.
-
-.. _django.core.urlresolvers.reverse: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
-.. _django.core.urlresolvers.reverse_lazy: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
diff --git a/docs/howto/setup.rst b/docs/howto/setup.rst
deleted file mode 100644
index f0127060..00000000
--- a/docs/howto/setup.rst
+++ /dev/null
@@ -1,73 +0,0 @@
-.. _setup:
-
-Setup
-=====
-
-Templates
----------
-
-Django REST framework uses a few templates for the HTML and plain text
-documenting renderers. You'll need to ensure ``TEMPLATE_LOADERS`` setting
-contains ``'django.template.loaders.app_directories.Loader'``.
-This will already be the case by default.
-
-You may customize the templates by creating a new template called
-``djangorestframework/api.html`` in your project, which should extend
-``djangorestframework/base.html`` and override the appropriate
-block tags. For example::
-
- {% extends "djangorestframework/base.html" %}
-
- {% block title %}My API{% endblock %}
-
- {% block branding %}
-
My API
- {% endblock %}
-
-
-Styling
--------
-
-Django REST framework requires `django.contrib.staticfiles`_ to serve it's css.
-If you're using Django 1.2 you'll need to use the seperate
-`django-staticfiles`_ package instead.
-
-You can override the styling by creating a file in your top-level static
-directory named ``djangorestframework/css/style.css``
-
-
-Markdown
---------
-
-`Python markdown`_ is not required but comes recommended.
-
-If markdown is installed your :class:`.Resource` descriptions can include
-`markdown formatting`_ which will be rendered by the self-documenting API.
-
-YAML
-----
-
-YAML support is optional, and requires `PyYAML`_.
-
-
-Login / Logout
---------------
-
-Django REST framework includes login and logout views that are needed if
-you're using the self-documenting API.
-
-Make sure you include the following in your `urlconf`::
-
- from django.conf.urls.defaults import patterns, url
-
- urlpatterns = patterns('',
- ...
- url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework'))
- )
-
-.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
-.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
-.. _URLObject: http://pypi.python.org/pypi/URLObject/
-.. _Python markdown: http://www.freewisdom.org/projects/python-markdown/
-.. _markdown formatting: http://daringfireball.net/projects/markdown/syntax
-.. _PyYAML: http://pypi.python.org/pypi/PyYAML
\ No newline at end of file
diff --git a/docs/howto/usingcurl.rst b/docs/howto/usingcurl.rst
deleted file mode 100644
index eeb8da06..00000000
--- a/docs/howto/usingcurl.rst
+++ /dev/null
@@ -1,30 +0,0 @@
-Using CURL with django-rest-framework
-=====================================
-
-`curl `_ is a great command line tool for making requests to URLs.
-
-There are a few things that can be helpful to remember when using CURL with django-rest-framework APIs.
-
-#. Curl sends an ``Accept: */*`` header by default::
-
- curl -X GET http://example.com/my-api/
-
-#. Setting the ``Accept:`` header on a curl request can be useful::
-
- curl -X GET -H 'Accept: application/json' http://example.com/my-api/
-
-#. The text/plain representation is useful for browsing the API::
-
- curl -X GET -H 'Accept: text/plain' http://example.com/my-api/
-
-#. ``POST`` and ``PUT`` requests can contain form data (ie ``Content-Type: application/x-www-form-urlencoded``)::
-
- curl -X PUT --data 'foo=bar' http://example.com/my-api/some-resource/
-
-#. Or any other content type::
-
- curl -X PUT -H 'Content-Type: application/json' --data-binary '{"foo":"bar"}' http://example.com/my-api/some-resource/
-
-#. You can use basic authentication to send the username and password::
-
- curl -X GET -H 'Accept: application/json' -u : http://example.com/my-api/
diff --git a/docs/howto/usingurllib2.rst b/docs/howto/usingurllib2.rst
deleted file mode 100644
index 6320dc20..00000000
--- a/docs/howto/usingurllib2.rst
+++ /dev/null
@@ -1,39 +0,0 @@
-Using urllib2 with Django REST Framework
-========================================
-
-Python's standard library comes with some nice modules
-you can use to test your api or even write a full client.
-
-Using the 'GET' method
-----------------------
-
-Here's an example which does a 'GET' on the `model-resource` example
-in the sandbox.::
-
- >>> import urllib2
- >>> r = urllib2.urlopen('htpp://rest.ep.io/model-resource-example')
- >>> r.getcode() # Check if the response was ok
- 200
- >>> print r.read() # Examin the response itself
- [{"url": "http://rest.ep.io/model-resource-example/1/", "baz": "sdf", "foo": true, "bar": 123}]
-
-Using the 'POST' method
------------------------
-
-And here's an example which does a 'POST' to create a new instance. First let's encode
-the data we want to POST. We'll use `urllib` for encoding and the `time` module
-to send the current time as as a string value for our POST.::
-
- >>> import urllib, time
- >>> d = urllib.urlencode((('bar', 123), ('baz', time.asctime())))
-
-Now use the `Request` class and specify the 'Content-type'::
-
- >>> req = urllib2.Request('http://rest.ep.io/model-resource-example/', data=d, headers={'Content-Type':'application/x-www-form-urlencoded'})
- >>> resp = urllib2.urlopen(req)
- >>> resp.getcode()
- 201
- >>> resp.read()
- '{"url": "http://rest.ep.io/model-resource-example/4/", "baz": "Fri Dec 30 18:22:52 2011", "foo": false, "bar": 123}'
-
-That should get you started to write a client for your own api.
diff --git a/docs/index.md b/docs/index.md
new file mode 100644
index 00000000..9bd90d8d
--- /dev/null
+++ b/docs/index.md
@@ -0,0 +1,62 @@
+Quickstart
+==========
+
+**TODO**
+
+Tutorial
+========
+
+* [1 - Serialization][tut-1]
+* [2 - Requests & Responses][tut-2]
+* [3 - Class based views][tut-3]
+* [4 - Authentication, permissions & throttling][tut-4]
+* [5 - Relationships & hyperlinked APIs][tut-5]
+* [6 - Resource orientated projects][tut-6]
+
+API Guide
+=========
+
+* [Requests][request]
+* [Responses][response]
+* [Views][views]
+* [Parsers][parsers]
+* [Renderers][renderers]
+* [Serializers][serializers]
+* [Authentication][authentication]
+* [Permissions][permissions]
+* [Status codes][status]
+
+Topics
+======
+
+* [Returning URLs][urls]
+* [CSRF][csrf]
+* [Form overloading][formoverloading]
+
+Other
+=====
+
+* Why REST framework
+* Contributing
+* Change Log
+
+[tut-1]: tutorial/1-serialization.md
+[tut-2]: tutorial/2-requests-and-responses.md
+[tut-3]: tutorial/3-class-based-views.md
+[tut-4]: tutorial/4-authentication-permissions-and-throttling.md
+[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
+[tut-6]: tutorial/6-resource-orientated-projects.md
+
+[request]: request.md
+[response]: response.md
+[views]: views.md
+[parsers]: parsers.md
+[renderers]: renderers.md
+[serializers]: serializers.md
+[authentication]: authentication.md
+[permissions]: permissions.md
+[status]: status.md
+
+[urls]: urls.md
+[csrf]: csrf.md
+[formoverloading]: formoverloading.md
diff --git a/docs/index.rst b/docs/index.rst
deleted file mode 100644
index a6745fca..00000000
--- a/docs/index.rst
+++ /dev/null
@@ -1,128 +0,0 @@
-.. meta::
- :description: A lightweight REST framework for Django.
- :keywords: django, python, REST, RESTful, API, interface, framework
-
-
-Django REST framework
-=====================
-
-Introduction
-------------
-
-Django REST framework is a lightweight REST framework for Django, that aims to make it easy to build well-connected, self-describing RESTful Web APIs.
-
-**Browse example APIs created with Django REST framework:** `The Sandbox `_
-
-Features:
----------
-
-* Automatically provides an awesome Django admin style `browse-able self-documenting API `_.
-* Clean, simple, views for Resources, using Django's new `class based views `_.
-* Support for ModelResources with out-of-the-box default implementations and input validation.
-* Pluggable :mod:`.parsers`, :mod:`renderers`, :mod:`authentication` and :mod:`permissions` - Easy to customise.
-* Content type negotiation using HTTP Accept headers.
-* Optional support for forms as input validation.
-* Modular architecture - MixIn classes can be used without requiring the :class:`.Resource` or :class:`.ModelResource` classes.
-
-Resources
----------
-
-**Project hosting:** `GitHub `_.
-
-* The ``djangorestframework`` package is `available on PyPI `_.
-* We have an active `discussion group `_.
-* Bug reports are handled on the `issue tracker `_.
-* There is a `Jenkins CI server `_ which tracks test status and coverage reporting. (Thanks Marko!)
-
-Any and all questions, thoughts, bug reports and contributions are *hugely appreciated*.
-
-Requirements
-------------
-
-* Python (2.5, 2.6, 2.7 supported)
-* Django (1.2, 1.3, 1.4 supported)
-* `django.contrib.staticfiles`_ (or `django-staticfiles`_ for Django 1.2)
-* `URLObject`_ >= 2.0.0
-* `Markdown`_ >= 2.1.0 (Optional)
-* `PyYAML`_ >= 3.10 (Optional)
-
-Installation
-------------
-
-You can install Django REST framework using ``pip`` or ``easy_install``::
-
- pip install djangorestframework
-
-Or get the latest development version using git::
-
- git clone git@github.com:tomchristie/django-rest-framework.git
-
-Setup
------
-
-To add Django REST framework to a Django project:
-
-* Ensure that the ``djangorestframework`` directory is on your ``PYTHONPATH``.
-* Add ``djangorestframework`` to your ``INSTALLED_APPS``.
-* Add the following to your URLconf. (To include the REST framework Login/Logout views.)::
-
- urlpatterns = patterns('',
- ...
- url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework'))
- )
-
-For more information on settings take a look at the :ref:`setup` section.
-
-Getting Started
----------------
-
-Using Django REST framework can be as simple as adding a few lines to your urlconf.
-
-The following example exposes your `MyModel` model through an api. It will provide two views:
-
- * A view which lists your model instances and simultaniously allows creation of instances
- from that view.
-
- * Another view which lets you view, update or delete your model instances individually.
-
-``urls.py``::
-
- from django.conf.urls.defaults import patterns, url
- from djangorestframework.resources import ModelResource
- from djangorestframework.views import ListOrCreateModelView, InstanceModelView
- from myapp.models import MyModel
-
- class MyResource(ModelResource):
- model = MyModel
-
- urlpatterns = patterns('',
- url(r'^$', ListOrCreateModelView.as_view(resource=MyResource)),
- url(r'^(?P[^/]+)/$', InstanceModelView.as_view(resource=MyResource)),
- )
-
-.. include:: howto.rst
-
-.. include:: library.rst
-
-
-.. include:: examples.rst
-
-.. toctree::
- :hidden:
-
- contents
-
-.. include:: ../CHANGELOG.rst
-
-Indices and tables
-------------------
-
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
-
-.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
-.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
-.. _URLObject: http://pypi.python.org/pypi/URLObject/
-.. _Markdown: http://pypi.python.org/pypi/Markdown/
-.. _PyYAML: http://pypi.python.org/pypi/PyYAML
diff --git a/docs/library.rst b/docs/library.rst
deleted file mode 100644
index b0309da0..00000000
--- a/docs/library.rst
+++ /dev/null
@@ -1,8 +0,0 @@
-Library
-=======
-
-.. toctree::
- :maxdepth: 1
- :glob:
-
- library/*
diff --git a/docs/library/authentication.rst b/docs/library/authentication.rst
deleted file mode 100644
index d159f605..00000000
--- a/docs/library/authentication.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`authentication`
-=====================
-
-.. automodule:: authentication
- :members:
diff --git a/docs/library/compat.rst b/docs/library/compat.rst
deleted file mode 100644
index 93fb081a..00000000
--- a/docs/library/compat.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`compat`
-=====================
-
-.. automodule:: compat
- :members:
diff --git a/docs/library/mixins.rst b/docs/library/mixins.rst
deleted file mode 100644
index 04bf66b0..00000000
--- a/docs/library/mixins.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`mixins`
-=====================
-
-.. automodule:: mixins
- :members:
diff --git a/docs/library/parsers.rst b/docs/library/parsers.rst
deleted file mode 100644
index 48d762a5..00000000
--- a/docs/library/parsers.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`parsers`
-==============
-
-.. automodule:: parsers
- :members:
diff --git a/docs/library/permissions.rst b/docs/library/permissions.rst
deleted file mode 100644
index c694d639..00000000
--- a/docs/library/permissions.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`permissions`
-=====================
-
-.. automodule:: permissions
- :members:
diff --git a/docs/library/renderers.rst b/docs/library/renderers.rst
deleted file mode 100644
index a9e72931..00000000
--- a/docs/library/renderers.rst
+++ /dev/null
@@ -1,10 +0,0 @@
-:mod:`renderers`
-================
-
-The renderers module provides a set of renderers that can be plugged in to a :class:`.Resource`.
-A renderer is responsible for taking the output of a View and serializing it to a given media type.
-A :class:`.Resource` can have a number of renderers, allow the same content to be serialized in a number
-of different formats depending on the requesting client's preferences, as specified in the HTTP Request's Accept header.
-
-.. automodule:: renderers
- :members:
diff --git a/docs/library/request.rst b/docs/library/request.rst
deleted file mode 100644
index 5e99826a..00000000
--- a/docs/library/request.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`request`
-=====================
-
-.. automodule:: request
- :members:
diff --git a/docs/library/resource.rst b/docs/library/resource.rst
deleted file mode 100644
index 2a95051b..00000000
--- a/docs/library/resource.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`resource`
-===============
-
-.. automodule:: resources
- :members:
diff --git a/docs/library/response.rst b/docs/library/response.rst
deleted file mode 100644
index c2fff5a7..00000000
--- a/docs/library/response.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`response`
-===============
-
-.. automodule:: response
- :members:
diff --git a/docs/library/reverse.rst b/docs/library/reverse.rst
deleted file mode 100644
index a2c29c48..00000000
--- a/docs/library/reverse.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`reverse`
-================
-
-.. automodule:: reverse
- :members:
diff --git a/docs/library/serializer.rst b/docs/library/serializer.rst
deleted file mode 100644
index 63dd3308..00000000
--- a/docs/library/serializer.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`serializer`
-=================
-
-.. automodule:: serializer
- :members:
diff --git a/docs/library/status.rst b/docs/library/status.rst
deleted file mode 100644
index 0c7596bc..00000000
--- a/docs/library/status.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`status`
-===============
-
-.. automodule:: status
- :members:
diff --git a/docs/library/utils.rst b/docs/library/utils.rst
deleted file mode 100644
index 653f24fd..00000000
--- a/docs/library/utils.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`utils`
-==============
-
-.. automodule:: utils
- :members:
diff --git a/docs/library/views.rst b/docs/library/views.rst
deleted file mode 100644
index 329b487b..00000000
--- a/docs/library/views.rst
+++ /dev/null
@@ -1,5 +0,0 @@
-:mod:`views`
-=====================
-
-.. automodule:: views
- :members:
diff --git a/docs/parsers.md b/docs/parsers.md
new file mode 100644
index 00000000..44e33105
--- /dev/null
+++ b/docs/parsers.md
@@ -0,0 +1,5 @@
+Parsers
+=======
+
+.parse(request)
+---------------
diff --git a/docs/renderers.md b/docs/renderers.md
new file mode 100644
index 00000000..20cdb8ad
--- /dev/null
+++ b/docs/renderers.md
@@ -0,0 +1,6 @@
+Renderers
+=========
+
+.render(response)
+-----------------
+
diff --git a/docs/request.md b/docs/request.md
new file mode 100644
index 00000000..b0491897
--- /dev/null
+++ b/docs/request.md
@@ -0,0 +1,76 @@
+Request
+=======
+
+> If you're doing REST-based web service stuff ... you should ignore request.POST.
+>
+> — Malcom Tredinnick, [Django developers group][1]
+
+The `Request` object in `djangorestframework` extends the standard `HttpRequest`, adding support for parsing multiple content types, allowing browser-based `PUT`, `DELETE` and other methods, and adding flexible per-request authentication.
+
+method
+------
+
+`request.method` returns the uppercased string representation of the request's HTTP method.
+
+Browser-based `PUT`, `DELETE` and other requests are supported, and can be made by using a hidden form field named `_method` in a regular `POST` form.
+
+
+
+content_type
+------------
+
+`request.content`, returns a string object representing the mimetype of the HTTP request's body, if one exists.
+
+
+
+DATA
+----
+
+`request.DATA` returns the parsed content of the request body. This is similar to the standard `HttpRequest.POST` attribute except that:
+
+1. It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
+2. It supports parsing multiple content types, rather than just form data. For example you can handle incoming json data in the same way that you handle incoming form data.
+
+FILES
+-----
+
+`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing that is used for `request.DATA`.
+
+This allows you to support file uploads from multiple content-types. For example you can write a parser that supports `POST`ing the raw content of a file, instead of using form-encoded file uploads.
+
+user
+----
+
+`request.user` returns a `django.contrib.auth.models.User` instance.
+
+auth
+----
+
+`request.auth` returns any additional authentication context that may not be contained in `request.user`. The exact behavior of `request.auth` depends on what authentication has been set in `request.authentication`. For many types of authentication this will simply be `None`, but it may also be an object representing a permission scope, an expiry time, or any other information that might be contained in a token-based authentication scheme.
+
+parsers
+-------
+
+`request.parsers` should be set to a list of `Parser` instances that can be used to parse the content of the request body.
+
+`request.parsers` may no longer be altered once `request.DATA`, `request.FILES` or `request.POST` have been accessed.
+
+If you're using the `djangorestframework.views.View` class... **[TODO]**
+
+stream
+------
+
+`request.stream` returns a stream representing the content of the request body.
+
+You will not typically need to access `request.stream`, unless you're writing a `Parser` class.
+
+authentication
+--------------
+
+`request.authentication` should be set to a list of `Authentication` instances that can be used to authenticate the request.
+
+`request.authentication` may no longer be altered once `request.user` or `request.auth` have been accessed.
+
+If you're using the `djangorestframework.views.View` class... **[TODO]**
+
+[1]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
\ No newline at end of file
diff --git a/docs/requirements.txt b/docs/requirements.txt
deleted file mode 100644
index 46a67149..00000000
--- a/docs/requirements.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-# Documentation requires Django & Sphinx, and their dependencies...
-
-Django>=1.2.4
-Jinja2==2.5.5
-Pygments==1.4
-Sphinx==1.0.7
-docutils==0.7
-wsgiref==0.1.2
diff --git a/docs/response.md b/docs/response.md
new file mode 100644
index 00000000..d77c9a0d
--- /dev/null
+++ b/docs/response.md
@@ -0,0 +1,27 @@
+Responses
+=========
+
+> HTTP has provisions for several mechanisms for "content negotiation" -- the process of selecting the best representation for a given response when there are multiple representations available. -- RFC 2616, Fielding et al.
+
+> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. -- Django documentation.
+
+Django REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
+
+The `Response` class subclasses Django's `TemplateResponse`. It works by allowing you to specify a serializer and a number of different renderers. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
+
+There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it does provide a better interface for returning Web API responses.
+
+Response(content, status, headers=None, serializer=None, renderers=None, format=None)
+-------------------------------------------------------------------------------------
+
+serializer
+----------
+
+renderers
+---------
+
+view
+----
+
+ImmediateResponse(...)
+----------------------
\ No newline at end of file
diff --git a/docs/serializers.md b/docs/serializers.md
new file mode 100644
index 00000000..23e37f40
--- /dev/null
+++ b/docs/serializers.md
@@ -0,0 +1,47 @@
+Serializers
+===========
+
+> 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.
+ - Russell Keith-Magee, [Django users group][1]
+
+Serializers provide a way of filtering the content of responses, prior to the response being rendered.
+
+They also allow us to use complex data such as querysets and model instances for the content of our responses, and convert that data into native python datatypes that can then be easily rendered into `JSON`, `XML` or whatever.
+
+REST framework includes a default `Serializer` class which gives you a powerful, generic way to control the output of your responses, but you can also write custom serializers for your data, or create other generic serialization strategies to suit the needs of your API.
+
+BaseSerializer
+--------------
+
+This is the base class for all serializers. If you want to provide your own custom serialization, override this class.
+
+.serialize()
+------------
+
+Serializer
+----------
+
+This is the default serializer.
+
+fields
+------
+
+include
+-------
+
+exclude
+-------
+
+rename
+------
+
+related_serializer
+------------------
+
+depth
+-----
+
+[1]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
diff --git a/docs/status.md b/docs/status.md
new file mode 100644
index 00000000..ca866cad
--- /dev/null
+++ b/docs/status.md
@@ -0,0 +1,17 @@
+Status Codes
+============
+
+> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
+ - RFC 2324
+
+REST framework provides a ...
+These are simply ...
+
+ from djangorestframework import status
+
+ def view(self):
+ return Response(status=status.HTTP_404_NOT_FOUND)
+
+For more information see [RFC 2616](1).
+
+[1]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
\ No newline at end of file
diff --git a/docs/templates/layout.html b/docs/templates/layout.html
deleted file mode 100644
index a59645f2..00000000
--- a/docs/templates/layout.html
+++ /dev/null
@@ -1,28 +0,0 @@
-{% extends "!layout.html" %}
-
-{%- if not embedded and docstitle %}
- {%- set titleprefix = docstitle|e + " - "|safe %}
-{%- else %}
- {%- set titleprefix = "" %}
-{%- endif %}
-
-{% block htmltitle %}{% if pagename == 'index' %}Django REST framework{% else %}{{ titleprefix }}{{ title|striptags|e }}{% endif %}{% endblock %}
-
-{% block extrahead %}
-{{ super() }}
-
-{% endblock %}
-{% block footer %}
-
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
new file mode 100644
index 00000000..55a9f679
--- /dev/null
+++ b/docs/tutorial/1-serialization.md
@@ -0,0 +1,236 @@
+# Tutorial 1: Serialization
+
+## Introduction
+
+This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together.
+
+## Getting started
+
+To get started, let's create a new project to work with.
+
+ django-admin.py startproject tutorial
+ cd tutorial
+
+Once that's done we can create an app that we'll use to create a simple Web API.
+
+ python manage.py startapp blog
+
+The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`.
+
+ DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': 'tmp.db',
+ 'USER': '',
+ 'PASSWORD': '',
+ 'HOST': '',
+ 'PORT': '',
+ }
+ }
+
+We'll also need to add our new `blog` app and the `djangorestframework` app to `INSTALLED_APPS`.
+
+ INSTALLED_APPS = (
+ ...
+ 'djangorestframework',
+ 'blog'
+ )
+
+We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our blog views.
+
+ urlpatterns = patterns('',
+ url(r'^', include('blog.urls')),
+ )
+
+Okay, we're ready to roll.
+
+## Creating a model to work with
+
+For the purposes of this tutorial we're going to start by creating a simple `Comment` model that is used to store comments against a blog post. Go ahead and edit the `blog` app's `models.py` file.
+
+ from django.db import models
+
+ class Comment(models.Model):
+ email = models.EmailField()
+ content = models.CharField(max_length=200)
+ created = models.DateTimeField(auto_now_add=True)
+
+Don't forget to sync the database for the first time.
+
+ python manage.py syncdb
+
+## Creating a Serializer class
+
+We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as `json`. We do this by declaring serializers, that work very similarly to Django's forms. Create a file in the project named `serializers.py` and add the following.
+
+ from blog import models
+ from djangorestframework import serializers
+
+
+ class CommentSerializer(serializers.Serializer):
+ email = serializers.EmailField()
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
+
+ def restore_object(self, attrs, instance=None):
+ """
+ Create or update a new comment instance.
+ """
+ if instance:
+ instance.email = attrs['email']
+ instance.content = attrs['content']
+ instance.created = attrs['created']
+ return instance
+ return models.Comment(**attrs)
+
+The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
+
+We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit.
+
+## Working with Serializers
+
+Before we go any further we'll familiarise ourselves with using our new Serializer class. Let's drop into the Django shell.
+
+ python manage.py shell
+
+Okay, once we've got a few imports out of the way, we'd better create a few comments to work with.
+
+ from blog.models import Comment
+ from blog.serializers import CommentSerializer
+ from djangorestframework.renderers import JSONRenderer
+ from djangorestframework.parsers import JSONParser
+
+ c1 = Comment(email='leila@example.com', content='nothing to say')
+ c2 = Comment(email='tom@example.com', content='foo bar')
+ c3 = Comment(email='anna@example.com', content='LOLZ!')
+ c1.save()
+ c2.save()
+ c3.save()
+
+We've now got a few comment instances to play with. Let's take a look at serializing one of those instances.
+
+ serializer = CommentSerializer(instance=c1)
+ serializer.data
+ # {'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
+
+At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
+
+ stream = JSONRenderer().render(serializer.data)
+ stream
+ # '{"email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
+
+Deserialization is similar. First we parse a stream into python native datatypes...
+
+ data = JSONParser().parse(stream)
+
+...then we restore those native datatypes into to a fully populated object instance.
+
+ serializer = CommentSerializer(data)
+ serializer.is_valid()
+ # True
+ serializer.object
+ #
+
+Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
+
+## Writing regular Django views using our Serializers
+
+Let's see how we can write some API views using our new Serializer class.
+We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into `json`.
+
+Edit the `blog/views.py` file, and add the following.
+
+ from blog.models import Comment
+ from blog.serializers import CommentSerializer
+ from djangorestframework.renderers import JSONRenderer
+ from djangorestframework.parsers import JSONParser
+ from django.http import HttpResponse
+
+
+ class JSONResponse(HttpResponse):
+ """
+ An HttpResponse that renders it's content into JSON.
+ """
+
+ def __init__(self, data, **kwargs):
+ content = JSONRenderer().render(data)
+ kwargs['content_type'] = 'application/json'
+ super(JSONResponse, self).__init__(content, **kwargs)
+
+
+The root of our API is going to be a view that supports listing all the existing comments, or creating a new comment.
+
+ def comment_root(request):
+ """
+ List all comments, or create a new comment.
+ """
+ if request.method == 'GET':
+ comments = Comment.objects.all()
+ serializer = CommentSerializer(instance=comments)
+ return JSONResponse(serializer.data)
+
+ elif request.method == 'POST':
+ data = JSONParser().parse(request)
+ serializer = CommentSerializer(data)
+ if serializer.is_valid():
+ comment = serializer.object
+ comment.save()
+ return JSONResponse(serializer.data, status=201)
+ else:
+ return JSONResponse(serializer.error_data, status=400)
+
+We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment.
+
+ def comment_instance(request, pk):
+ """
+ Retrieve, update or delete a comment instance.
+ """
+ try:
+ comment = Comment.objects.get(pk=pk)
+ except Comment.DoesNotExist:
+ return HttpResponse(status=404)
+
+ if request.method == 'GET':
+ serializer = CommentSerializer(instance=comment)
+ return JSONResponse(serializer.data)
+
+ elif request.method == 'PUT':
+ data = JSONParser().parse(request)
+ serializer = CommentSerializer(data, instance=comment)
+ if serializer.is_valid():
+ comment = serializer.object
+ comment.save()
+ return JSONResponse(serializer.data)
+ else:
+ return JSONResponse(serializer.error_data, status=400)
+
+ elif request.method == 'DELETE':
+ comment.delete()
+ return HttpResponse(status=204)
+
+Finally we need to wire these views up, in the `tutorial/urls.py` file.
+
+ from django.conf.urls import patterns, url
+
+ urlpatterns = patterns('blog.views',
+ url(r'^$', 'comment_root'),
+ url(r'^(?P[0-9]+)$', 'comment_instance')
+ )
+
+It's worth noting that there's a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
+
+## Testing our first attempt at a Web API
+
+**TODO: Describe using runserver and making example requests from console**
+
+**TODO: Describe opening in a web browser and viewing json output**
+
+## Where are we now
+
+We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views.
+
+Our API views don't do anything particularly special at the moment, beyond serve `json` responses, and there's some error handling edge cases we'd still like to clean up, but it's a functioning Web API.
+
+We'll see how we can start to improve things in [part 2 of the tutorial][1].
+
+[1]: 2-requests-and-responses.md
\ No newline at end of file
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
new file mode 100644
index 00000000..2bb6c20e
--- /dev/null
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -0,0 +1,137 @@
+# Tutorial 2: Request and Response objects
+
+From this point we're going to really start covering the core of REST framework.
+Let's introduce a couple of essential building blocks.
+
+## Request objects
+
+REST framework intoduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.DATA` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
+
+ request.POST # Only handles form data. Only works for 'POST' method.
+ request.DATA # Handles arbitrary data. Works any HTTP request with content.
+
+## Response objects
+
+REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
+
+ return Response(data) # Renders to content type as requested by the client.
+
+## Status codes
+
+Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as `HTTP_400_BAD_REQUEST` in the `status` module. It's a good idea to use these throughout rather than using numeric identifiers.
+
+## Wrapping API views
+
+REST framework provides two wrappers you can use to write API views.
+
+1. The `@api_view` decorator for working with function based views.
+2. The `APIView` class for working with class based views.
+
+These wrappers provide a few bits of functionality such as making sure you recieve `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
+
+The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
+
+
+## Pulling it all together
+
+Okay, let's go ahead and start using these new components to write a few views.
+
+ from djangorestframework.decorators import api_view
+ from djangorestframework.status import *
+
+ @api_view(allow=['GET', 'POST'])
+ def comment_root(request):
+ """
+ List all comments, or create a new comment.
+ """
+ if request.method == 'GET':
+ comments = Comment.objects.all()
+ serializer = CommentSerializer(instance=comments)
+ return Response(serializer.data)
+
+ elif request.method == 'POST':
+ serializer = CommentSerializer(request.DATA)
+ if serializer.is_valid():
+ comment = serializer.object
+ comment.save()
+ return Response(serializer.data, status=HTTP_201_CREATED)
+ else:
+ return Response(serializer.error_data, status=HTTP_400_BAD_REQUEST)
+
+
+Our instance view is an improvement over the previous example. It's slightly more concise, and the code now feels very similar to if we were working with the Forms API.
+
+ @api_view(allow=['GET', 'PUT', 'DELETE'])
+ def comment_instance(request, pk):
+ """
+ Retrieve, update or delete a comment instance.
+ """
+ try:
+ comment = Comment.objects.get(pk=pk)
+ except Comment.DoesNotExist:
+ return Response(status=HTTP_404_NOT_FOUND)
+
+ if request.method == 'GET':
+ serializer = CommentSerializer(instance=comment)
+ return Response(serializer.data)
+
+ elif request.method == 'PUT':
+ serializer = CommentSerializer(request.DATA, instance=comment)
+ if serializer.is_valid():
+ comment = serializer.object
+ comment.save()
+ return Response(serializer.data)
+ else:
+ return Response(serializer.error_data, status=HTTP_400_BAD_REQUEST)
+
+ elif request.method == 'DELETE':
+ comment.delete()
+ return Response(status=HTTP_204_NO_CONTENT)
+
+This should all feel very familiar - it looks a lot like working with forms in regular Django views.
+
+Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.DATA` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
+
+## Adding optional format suffixes to our URLs
+
+To take advantage of that, let's add support for format suffixes to our API endpoints, so that we can use URLs that explicitly refer to a given format. That means our API will be able to handle URLs such as [http://example.com/api/items/4.json][1].
+
+Start by adding a `format` keyword argument to both of the views, like so.
+
+ def comment_root(request, format=None):
+
+and
+
+ def comment_instance(request, pk, format=None):
+
+Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
+
+ from djangorestframework.urlpatterns import format_suffix_patterns
+
+ urlpatterns = patterns('blogpost.views',
+ url(r'^$', 'comment_root'),
+ url(r'^(?P[0-9]+)$', 'comment_instance')
+ )
+
+ urlpatterns = format_suffix_patterns(urlpatterns)
+
+We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of refering to a specific format.
+
+## How's it looking?
+
+Go ahead and test the API from the command line, as we did in [tutorial part 1][2]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests.
+
+**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
+
+Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3].
+
+**TODO: Describe browseable API awesomeness**
+
+## What's next?
+
+In [tutorial part 3][4], we'll start using class based views, and see how generic views reduce the amount of code we need to write.
+
+[1]: http://example.com/api/items/4.json
+[2]: 1-serialization.md
+[3]: http://127.0.0.1:8000/
+[4]: 3-class-based-views.md
\ No newline at end of file
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
new file mode 100644
index 00000000..e56c7847
--- /dev/null
+++ b/docs/tutorial/3-class-based-views.md
@@ -0,0 +1,137 @@
+# Tutorial 3: Using Class Based Views
+
+We can also write our API views using class based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code [DRY][1].
+
+## Rewriting our API using class based views
+
+We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.
+
+ from blog.models import Comment
+ from blog.serializers import ComentSerializer
+ from django.http import Http404
+ from djangorestframework.views import APIView
+ from djangorestframework.response import Response
+ from djangorestframework.status import *
+
+ class CommentRoot(views.APIView):
+ """
+ List all comments, or create a new comment.
+ """
+ def get(self, request, format=None):
+ comments = Comment.objects.all()
+ serializer = ComentSerializer(instance=comments)
+ return Response(serializer.data)
+
+ def post(self, request, format=None)
+ serializer = ComentSerializer(request.DATA)
+ if serializer.is_valid():
+ comment = serializer.object
+ comment.save()
+ return Response(serializer.serialized, status=HTTP_201_CREATED)
+ else:
+ return Response(serializer.serialized_errors, status=HTTP_400_BAD_REQUEST)
+
+So far, so good. It looks pretty similar to the previous case, but we've got better seperation between the different HTTP methods. We'll also need to update the instance view.
+
+ class CommentInstance(views.APIView):
+ """
+ Retrieve, update or delete a comment instance.
+ """
+
+ def get_object(self, pk):
+ try:
+ return Poll.objects.get(pk=pk)
+ except Poll.DoesNotExist:
+ raise Http404
+
+ def get(self, request, pk, format=None):
+ comment = self.get_object(pk)
+ serializer = CommentSerializer(instance=comment)
+ return Response(serializer.data)
+
+ def put(self, request, pk, format=None):
+ comment = self.get_object(pk)
+ serializer = CommentSerializer(request.DATA, instance=comment)
+ if serializer.is_valid():
+ comment = serializer.deserialized
+ comment.save()
+ return Response(serializer.data)
+ else:
+ return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
+
+ def delete(self, request, pk, format=None):
+ comment = self.get_object(pk)
+ comment.delete()
+ return Response(status=HTTP_204_NO_CONTENT)
+
+That's looking good. Again, it's still pretty similar to the function based view right now.
+
+Since we're now working with class based views, rather than function based views, we'll also need to update our urlconf slightly.
+
+ from blogpost import views
+ from djangorestframework.urlpatterns import format_suffix_patterns
+
+ urlpatterns = patterns('',
+ url(r'^$', views.CommentRoot.as_view()),
+ url(r'^(?P[0-9]+)$', views.CommentInstance.as_view())
+ )
+
+ urlpatterns = format_suffix_patterns(urlpatterns)
+
+Okay, we're done. If you run the development server everything should be working just as before.
+
+## Using mixins
+
+One of the big wins of using class based views is that it allows us to easily compose reusable bits of behaviour.
+
+The create/retrieve/update/delete operations that we've been using so far is going to be pretty simliar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
+
+We can compose those mixin classes, to recreate our existing API behaviour with less code.
+
+ from blog.models import Comment
+ from blog.serializers import CommentSerializer
+ from djangorestframework import mixins, views
+
+ class CommentRoot(mixins.ListModelQuerysetMixin,
+ mixins.CreateModelInstanceMixin,
+ views.BaseRootAPIView):
+ model = Comment
+ serializer_class = CommentSerializer
+
+ get = list
+ post = create
+
+ class CommentInstance(mixins.RetrieveModelInstanceMixin,
+ mixins.UpdateModelInstanceMixin,
+ mixins.DestroyModelInstanceMixin,
+ views.BaseInstanceAPIView):
+ model = Comment
+ serializer_class = CommentSerializer
+
+ get = retrieve
+ put = update
+ delete = destroy
+
+## Reusing generic class based views
+
+That's a lot less code than before, but we can go one step further still. REST framework also provides a set of already mixed-in views.
+
+ from blog.models import Comment
+ from blog.serializers import CommentSerializer
+ from djangorestframework import views
+
+ class CommentRoot(views.RootAPIView):
+ model = Comment
+ serializer_class = CommentSerializer
+
+ class CommentInstance(views.InstanceAPIView):
+ model = Comment
+ serializer_class = CommentSerializer
+
+Wow, that's pretty concise. We've got a huge amount for free, and our code looks like
+good, clean, idomatic Django.
+
+Next we'll move onto [part 4 of the tutorial][2], where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
+
+[1]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
+[2]: 4-authentication-permissions-and-throttling.md
diff --git a/docs/tutorial/4-authentication-permissions-and-throttling.md b/docs/tutorial/4-authentication-permissions-and-throttling.md
new file mode 100644
index 00000000..5c37ae13
--- /dev/null
+++ b/docs/tutorial/4-authentication-permissions-and-throttling.md
@@ -0,0 +1,3 @@
+[part 5][5]
+
+[5]: 5-relationships-and-hyperlinked-apis.md
\ No newline at end of file
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
new file mode 100644
index 00000000..3d9598d7
--- /dev/null
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -0,0 +1,9 @@
+**TODO**
+
+* Create BlogPost model
+* Demonstrate nested relationships
+* Demonstrate and describe hyperlinked relationships
+
+[part 6][1]
+
+[1]: 6-resource-orientated-projects.md
diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md
new file mode 100644
index 00000000..ce51cce5
--- /dev/null
+++ b/docs/tutorial/6-resource-orientated-projects.md
@@ -0,0 +1,49 @@
+serializers.py
+
+ class BlogPostSerializer(URLModelSerializer):
+ class Meta:
+ model = BlogPost
+
+ class CommentSerializer(URLModelSerializer):
+ class Meta:
+ model = Comment
+
+resources.py
+
+ class BlogPostResource(ModelResource):
+ serializer_class = BlogPostSerializer
+ model = BlogPost
+ permissions = [AdminOrAnonReadonly()]
+ throttles = [AnonThrottle(rate='5/min')]
+
+ class CommentResource(ModelResource):
+ serializer_class = CommentSerializer
+ model = Comment
+ permissions = [AdminOrAnonReadonly()]
+ throttles = [AnonThrottle(rate='5/min')]
+
+Now that we're using Resources rather than Views, we don't need to design the urlconf ourselves. The conventions for wiring up resources into views and urls are handled automatically. All we need to do is register the appropriate resources with a router, and let it do the rest. Here's our re-wired `urls.py` file.
+
+ from blog import resources
+ from djangorestframework.routers import DefaultRouter
+
+ router = DefaultRouter()
+ router.register(resources.BlogPostResource)
+ router.register(resources.CommentResource)
+ urlpatterns = router.urlpatterns
+
+## Trade-offs between views vs resources.
+
+Writing resource-orientated code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write.
+
+The trade-off is that the behaviour is less explict. It can be more difficult to determine what code path is being followed, or where to override some behaviour.
+
+## Onwards and upwards.
+
+We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
+
+* Contribute on GitHub by reviewing issues, and submitting issues or pull requests.
+* Join the REST framework group, and help build the community.
+* Follow me on Twitter and say hi.
+
+Now go build something great.
\ No newline at end of file
diff --git a/docs/urls.md b/docs/urls.md
new file mode 100644
index 00000000..1828dd68
--- /dev/null
+++ b/docs/urls.md
@@ -0,0 +1,42 @@
+Returning URIs from your Web APIs
+=================================
+
+> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
+> -- Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures.
+
+As a rule, it's probably better practice to return absolute URIs from you web APIs, eg. "http://example.com/foobar", rather than returning relative URIs, eg. "/foobar".
+
+The advantages of doing so are:
+
+* It's more explicit.
+* It leaves less work for your API clients.
+* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
+* It allows use to easily do things like markup HTML representations with hyperlinks.
+
+Django REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
+
+There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
+
+reverse(viewname, request, ...)
+-------------------------------
+
+Has the same behavior as [`django.core.urlresolvers.reverse`](1), except that it returns a fully qualified URL, using the request to determine the host and port.
+
+ from djangorestframework.utils import reverse
+ from djangorestframework.views import View
+
+ class MyView(View):
+ def get(self, request):
+ context = {
+ ...
+ 'url': reverse('year-summary', request, args=[1945])
+ }
+ return Response(context)
+
+reverse_lazy(viewname, request, ...)
+------------------------------------
+
+Has the same behavior as [`django.core.urlresolvers.reverse_lazy`](2), except that it returns a fully qualified URL, using the request to determine the host and port.
+
+[1]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
+[1]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
\ No newline at end of file
diff --git a/docs/views.md b/docs/views.md
new file mode 100644
index 00000000..d227339e
--- /dev/null
+++ b/docs/views.md
@@ -0,0 +1,43 @@
+Views
+=====
+
+REST framework provides a simple `View` class, built on Django's `django.generics.views.View`. The `View` class ensures five main things:
+
+1. Any requests inside the view will become `Request` instances.
+2. `Request` instances will have their `renderers` and `authentication` attributes automatically set.
+3. `Response` instances will have their `parsers` and `serializer` attributes automatically set.
+4. `ImmediateResponse` exceptions will be caught and returned as regular responses.
+5. Any permissions provided will be checked prior to passing the request to a handler method.
+
+Additionally there are a some minor extras, such as providing a default `options` handler, setting some common headers on the response prior to return, and providing the useful `initial()` and `final()` hooks.
+
+View
+----
+
+.get(), .post(), .put(), .delete() etc...
+-----------------------------------------
+
+.initial(request, *args, **kwargs)
+----------------------------------
+
+.final(request, response, *args, **kwargs)
+------------------------------------------
+
+.parsers
+--------
+
+.renderers
+----------
+
+.serializer
+-----------
+
+.authentication
+---------------
+
+.permissions
+------------
+
+.headers
+--------
+
--
cgit v1.2.3
From deedf6957d14c2808c00a009ac2c1d4528cb80c9 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 1 Sep 2012 20:26:27 +0100
Subject: REST framework 2 docs
---
docs/api-guide/contentnegotiation.md | 1 +
docs/api-guide/exceptions.md | 3 +
docs/api-guide/parsers.md | 3 +
docs/api-guide/renderers.md | 4 +
docs/api-guide/requests.md | 66 ++++++++++
docs/api-guide/responses.md | 23 ++++
docs/api-guide/serializers.md | 241 +++++++++++++++++++++++++++++++++++
docs/api-guide/status-codes.md | 93 ++++++++++++++
docs/api-guide/urls.md | 41 ++++++
docs/api-guide/views.md | 39 ++++++
docs/csrf.md | 4 -
docs/formoverloading.md | 46 -------
docs/index.md | 132 +++++++++++++++----
docs/mkdocs.py | 56 ++++++++
docs/parsers.md | 5 -
docs/renderers.md | 6 -
docs/request.md | 76 -----------
docs/response.md | 27 ----
docs/serializers.md | 47 -------
docs/status.md | 17 ---
docs/template.html | 150 ++++++++++++++++++++++
docs/topics/csrf.md | 12 ++
docs/topics/formoverloading.md | 43 +++++++
docs/urls.md | 42 ------
docs/views.md | 43 -------
25 files changed, 880 insertions(+), 340 deletions(-)
create mode 100644 docs/api-guide/contentnegotiation.md
create mode 100644 docs/api-guide/exceptions.md
create mode 100644 docs/api-guide/parsers.md
create mode 100644 docs/api-guide/renderers.md
create mode 100644 docs/api-guide/requests.md
create mode 100644 docs/api-guide/responses.md
create mode 100644 docs/api-guide/serializers.md
create mode 100644 docs/api-guide/status-codes.md
create mode 100644 docs/api-guide/urls.md
create mode 100644 docs/api-guide/views.md
delete mode 100644 docs/csrf.md
delete mode 100644 docs/formoverloading.md
create mode 100755 docs/mkdocs.py
delete mode 100644 docs/parsers.md
delete mode 100644 docs/renderers.md
delete mode 100644 docs/request.md
delete mode 100644 docs/response.md
delete mode 100644 docs/serializers.md
delete mode 100644 docs/status.md
create mode 100644 docs/template.html
create mode 100644 docs/topics/csrf.md
create mode 100644 docs/topics/formoverloading.md
delete mode 100644 docs/urls.md
delete mode 100644 docs/views.md
(limited to 'docs')
diff --git a/docs/api-guide/contentnegotiation.md b/docs/api-guide/contentnegotiation.md
new file mode 100644
index 00000000..f01627d8
--- /dev/null
+++ b/docs/api-guide/contentnegotiation.md
@@ -0,0 +1 @@
+> HTTP has provisions for several mechanisms for "content negotiation" -- the process of selecting the best representation for a given response when there are multiple representations available. -- RFC 2616, Fielding et al.
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
new file mode 100644
index 00000000..d41327c6
--- /dev/null
+++ b/docs/api-guide/exceptions.md
@@ -0,0 +1,3 @@
+# Exceptions
+
+
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
new file mode 100644
index 00000000..2edc11de
--- /dev/null
+++ b/docs/api-guide/parsers.md
@@ -0,0 +1,3 @@
+# Parsers
+
+## .parse(request)
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
new file mode 100644
index 00000000..5a66da69
--- /dev/null
+++ b/docs/api-guide/renderers.md
@@ -0,0 +1,4 @@
+# Renderers
+
+## .render(response)
+
diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md
new file mode 100644
index 00000000..67ddfdac
--- /dev/null
+++ b/docs/api-guide/requests.md
@@ -0,0 +1,66 @@
+# Requests
+
+> If you're doing REST-based web service stuff ... you should ignore request.POST.
+>
+> — Malcom Tredinnick, [Django developers group][cite]
+
+REST framework's `Request` class extends the standard `HttpRequest`, adding support for parsing multiple content types, allowing browser-based `PUT`, `DELETE` and other methods, and adding flexible per-request authentication.
+
+## .method
+
+`request.method` returns the uppercased string representation of the request's HTTP method.
+
+Browser-based `PUT`, `DELETE` and other requests are supported, and can be made by using a hidden form field named `_method` in a regular `POST` form.
+
+
+
+## .content_type
+
+`request.content`, returns a string object representing the mimetype of the HTTP request's body, if one exists.
+
+
+
+## .DATA
+
+`request.DATA` returns the parsed content of the request body. This is similar to the standard `HttpRequest.POST` attribute except that:
+
+1. It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
+2. It supports parsing multiple content types, rather than just form data. For example you can handle incoming json data in the same way that you handle incoming form data.
+
+## .FILES
+
+`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing that is used for `request.DATA`.
+
+This allows you to support file uploads from multiple content-types. For example you can write a parser that supports `POST`ing the raw content of a file, instead of using form-encoded file uploads.
+
+## .user
+
+`request.user` returns a `django.contrib.auth.models.User` instance.
+
+## .auth
+
+`request.auth` returns any additional authentication context that may not be contained in `request.user`. The exact behavior of `request.auth` depends on what authentication has been set in `request.authentication`. For many types of authentication this will simply be `None`, but it may also be an object representing a permission scope, an expiry time, or any other information that might be contained in a token-based authentication scheme.
+
+## .parsers
+
+`request.parsers` should be set to a list of `Parser` instances that can be used to parse the content of the request body.
+
+`request.parsers` may no longer be altered once `request.DATA`, `request.FILES` or `request.POST` have been accessed.
+
+If you're using the `djangorestframework.views.View` class... **[TODO]**
+
+## .stream
+
+`request.stream` returns a stream representing the content of the request body.
+
+You will not typically need to access `request.stream`, unless you're writing a `Parser` class.
+
+## .authentication
+
+`request.authentication` should be set to a list of `Authentication` instances that can be used to authenticate the request.
+
+`request.authentication` may no longer be altered once `request.user` or `request.auth` have been accessed.
+
+If you're using the `djangorestframework.views.View` class... **[TODO]**
+
+[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
\ No newline at end of file
diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md
new file mode 100644
index 00000000..38f6e8cb
--- /dev/null
+++ b/docs/api-guide/responses.md
@@ -0,0 +1,23 @@
+# Responses
+
+> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
+>
+> — [Django documentation][cite]
+
+REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
+
+The `Response` class subclasses Django's `TemplateResponse`. `Response` objects are initialised with content, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
+
+There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it does provide a better interface for returning Web API responses.
+
+## Response(content, headers=None, renderers=None, view=None, format=None, status=None)
+
+
+## .renderers
+
+## .view
+
+## .format
+
+
+[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/
\ No newline at end of file
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
new file mode 100644
index 00000000..377b0c10
--- /dev/null
+++ b/docs/api-guide/serializers.md
@@ -0,0 +1,241 @@
+# Serializers
+
+> 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.
+>
+> — Russell Keith-Magee, [Django users group][cite]
+
+Serializers allow complex data such as querysets and model instances to be converted to native python datatypes that can then be easily rendered into `JSON`, `XML` or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
+
+REST framework's serializers work very similarly to Django's `Form` and `ModelForm` classes. It provides a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
+
+## Declaring Serializers
+
+Let's start by creating a simple object we can use for example purposes:
+
+ class Comment(object):
+ def __init__(self, email, content, created=None):
+ self.email = email
+ self.content = content
+ self.created = created or datetime.datetime.now()
+
+ comment = Comment(email='leila@example.com', content='foo bar')
+
+We'll declare a serializer that we can use to serialize and deserialize `Comment` objects.
+Declaring a serializer looks very similar to declaring a form:
+
+ class CommentSerializer(serializers.Serializer):
+ email = serializers.EmailField()
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
+
+ def restore_object(self, attrs, instance=None):
+ if instance:
+ instance.title = attrs['title']
+ instance.content = attrs['content']
+ instance.created = attrs['created']
+ return instance
+ return Comment(**attrs)
+
+The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. The `restore_object` method is optional, and is only required if we want our serializer to support deserialization.
+
+## Serializing objects
+
+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.data
+ # {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
+
+At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
+
+ stream = JSONRenderer().render(data)
+ stream
+ # '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
+
+## Deserializing objects
+
+Deserialization is similar. First we parse a stream into python native datatypes...
+
+ data = JSONParser().parse(stream)
+
+...then we restore those native datatypes into a fully populated object instance.
+
+ serializer = CommentSerializer(data)
+ serializer.is_valid()
+ # True
+ serializer.object
+ #
+ >>> serializer.deserialize('json', stream)
+
+## 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.
+
+**TODO: Describe validation in more depth**
+
+## Dealing with nested objects
+
+The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects,
+where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
+
+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)
+
+
+ class CommentSerializer(serializers.Serializer):
+ user = serializers.UserSerializer()
+ title = serializers.CharField()
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
+
+ def restore_object(self, attrs, instance=None):
+ return Comment(**attrs)
+
+## Creating custom fields
+
+If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects.
+
+The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation.
+
+Let's look at an example of serializing a class that represents an RGB color value:
+
+ class Color(object):
+ """
+ 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)
+ self.red, self.green, self.blue = red, green, blue
+
+ class ColourField(Field):
+ """
+ Color objects are serialized into "rgb(#, #, #)" notation.
+ """
+
+ def to_native(self, obj):
+ return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
+
+ def from_native(self, data):
+ data = data.strip('rgb(').rstrip(')')
+ red, green, blue = [int(col) for col in data.split(',')]
+ return Color(red, green, blue)
+
+
+By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`.
+
+As an example, let's create a field that can be used represent the class name of the object being serialized:
+
+ class ClassNameField(Field):
+ def field_to_native(self, obj, field_name):
+ """
+ Serialize the object's class name, not an attribute of the object.
+ """
+ return obj.__class__.__name__
+
+ def field_from_native(self, data, field_name, into):
+ """
+ We don't want to set anything when we revert this field.
+ """
+ pass
+
+---
+
+# 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.
+
+ class AccountSerializer(ModelSerializer):
+ class Meta:
+ model = Account
+
+**[TODO: Explain model field to serializer field mapping in more detail]**
+
+## Specifying fields explicitly
+
+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(ModelSerializer):
+ url = CharField(source='get_absolute_url', readonly=True)
+ group = NaturalKeyField()
+
+ class Meta:
+ model = Account
+
+Extra fields can corrospond to any property or callable on the model.
+
+## Relational fields
+
+When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation is to use the primary keys of the related instances.
+
+Alternative representations include serializing using natural keys, serializing complete nested representations, or serializing using a custom representation, such as a URL that uniquely identifies the model instances.
+
+The `PrimaryKeyField` and `NaturalKeyField` fields provide alternative flat representations.
+
+The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations.
+
+The `RelatedField` class may be subclassed to create a custom represenation of a relationship. The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported.
+
+All the relational fields may be used for any relationship or reverse relationship on a model.
+
+## Specifying which fields should be included
+
+If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
+
+For example:
+
+ class AccountSerializer(ModelSerializer):
+ class Meta:
+ model = Account
+ exclude = ('id',)
+
+The `fields` and `exclude` options may also be set by passing them to the `serialize()` method.
+
+**[TODO: Possibly only allow .serialize(fields=…) in FixtureSerializer for backwards compatability, but remove for ModelSerializer]**
+
+## Specifiying nested serialization
+
+The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `nested` option:
+
+ class AccountSerializer(ModelSerializer):
+ class Meta:
+ model = Account
+ exclude = ('id',)
+ nested = True
+
+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.
+
+When serializing objects using a nested representation any occurances of recursion will be recognised, and will fall back to using a flat representation.
+
+The `nested` option may also be set by passing it to the `serialize()` method.
+
+**[TODO: Possibly only allow .serialize(nested=…) in FixtureSerializer]**
+
+## Customising the default fields used by a ModelSerializer
+
+ class AccountSerializer(ModelSerializer):
+ class Meta:
+ model = Account
+
+ def get_nested_field(self, model_field):
+ return ModelSerializer()
+
+ def get_related_field(self, model_field):
+ return NaturalKeyField()
+
+ def get_field(self, model_field):
+ return Field()
+
+
+[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md
new file mode 100644
index 00000000..c1d45905
--- /dev/null
+++ b/docs/api-guide/status-codes.md
@@ -0,0 +1,93 @@
+# Status Codes
+
+> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
+>
+> — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol
+
+Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.
+
+ from djangorestframework import status
+
+ def empty_view(self):
+ content = {'please move along': 'nothing to see here'}
+ return Response(content, status=status.HTTP_404_NOT_FOUND)
+
+The full set of HTTP status codes included in the `status` module is listed below.
+
+For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
+and [RFC 6585][rfc6585].
+
+## Informational - 1xx
+
+This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.
+
+ HTTP_100_CONTINUE
+ HTTP_101_SWITCHING_PROTOCOLS
+
+## Successful - 2xx
+
+This class of status code indicates that the client's request was successfully received, understood, and accepted.
+
+ HTTP_200_OK
+ HTTP_201_CREATED
+ HTTP_202_ACCEPTED
+ HTTP_203_NON_AUTHORITATIVE_INFORMATION
+ HTTP_204_NO_CONTENT
+ HTTP_205_RESET_CONTENT
+ HTTP_206_PARTIAL_CONTENT
+
+## Redirection - 3xx
+
+This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
+
+ HTTP_300_MULTIPLE_CHOICES
+ HTTP_301_MOVED_PERMANENTLY
+ HTTP_302_FOUND
+ HTTP_303_SEE_OTHER
+ HTTP_304_NOT_MODIFIED
+ HTTP_305_USE_PROXY
+ HTTP_306_RESERVED
+ HTTP_307_TEMPORARY_REDIRECT
+
+## Client Error - 4xx
+
+The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
+
+ HTTP_400_BAD_REQUEST
+ HTTP_401_UNAUTHORIZED
+ HTTP_402_PAYMENT_REQUIRED
+ HTTP_403_FORBIDDEN
+ HTTP_404_NOT_FOUND
+ HTTP_405_METHOD_NOT_ALLOWED
+ HTTP_406_NOT_ACCEPTABLE
+ HTTP_407_PROXY_AUTHENTICATION_REQUIRED
+ HTTP_408_REQUEST_TIMEOUT
+ HTTP_409_CONFLICT
+ HTTP_410_GONE
+ HTTP_411_LENGTH_REQUIRED
+ HTTP_412_PRECONDITION_FAILED
+ HTTP_413_REQUEST_ENTITY_TOO_LARGE
+ HTTP_414_REQUEST_URI_TOO_LONG
+ HTTP_415_UNSUPPORTED_MEDIA_TYPE
+ HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
+ HTTP_417_EXPECTATION_FAILED
+ HTTP_428_PRECONDITION_REQUIRED
+ HTTP_429_TOO_MANY_REQUESTS
+ HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
+
+## Server Error - 5xx
+
+Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
+
+ HTTP_500_INTERNAL_SERVER_ERROR
+ HTTP_501_NOT_IMPLEMENTED
+ HTTP_502_BAD_GATEWAY
+ HTTP_503_SERVICE_UNAVAILABLE
+ HTTP_504_GATEWAY_TIMEOUT
+ HTTP_505_HTTP_VERSION_NOT_SUPPORTED
+ HTTP_511_NETWORD_AUTHENTICATION_REQUIRED
+
+
+[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt
+[rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
+[rfc6585]: http://tools.ietf.org/html/rfc6585
diff --git a/docs/api-guide/urls.md b/docs/api-guide/urls.md
new file mode 100644
index 00000000..c39ff8f6
--- /dev/null
+++ b/docs/api-guide/urls.md
@@ -0,0 +1,41 @@
+# Returning URIs from your Web APIs
+
+> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
+>
+> — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite]
+
+As a rule, it's probably better practice to return absolute URIs from you web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`.
+
+The advantages of doing so are:
+
+* It's more explicit.
+* It leaves less work for your API clients.
+* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
+* It allows use to easily do things like markup HTML representations with hyperlinks.
+
+REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
+
+There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
+
+## reverse(viewname, request, *args, **kwargs)
+
+Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
+
+ from djangorestframework.utils import reverse
+ from djangorestframework.views import APIView
+
+ class MyView(APIView):
+ def get(self, request):
+ content = {
+ ...
+ 'url': reverse('year-summary', request, args=[1945])
+ }
+ return Response(content)
+
+## reverse_lazy(viewname, request, *args, **kwargs)
+
+Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
+
+[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
+[reverse]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
+[reverse-lazy]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
\ No newline at end of file
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
new file mode 100644
index 00000000..dd1dbebe
--- /dev/null
+++ b/docs/api-guide/views.md
@@ -0,0 +1,39 @@
+> Django's class based views are a welcome departure from the old-style views.
+>
+> — [Reinout van Rees][cite]
+
+# Views
+
+REST framework provides a simple `APIView` class, built on Django's `django.generics.views.View`. The `APIView` class ensures five main things:
+
+1. Any requests inside the view will become `Request` instances.
+2. `Request` instances will have their `renderers` and `authentication` attributes automatically set.
+3. `Response` instances will have their `parsers` and `serializer` attributes automatically set.
+4. `APIException` exceptions will be caught and return appropriate responses.
+5. Any permissions provided will be checked prior to passing the request to a handler method.
+
+Additionally there are a some minor extras, such as providing a default `options` handler, setting some common headers on the response prior to return, and providing the useful `initial()` and `final()` hooks.
+
+## APIView
+
+## Method handlers
+
+Describe that APIView handles regular .get(), .post(), .put(), .delete() etc...
+
+## .initial(request, *args, **kwargs)
+
+## .final(request, response, *args, **kwargs)
+
+## .parsers
+
+## .renderers
+
+## .serializer
+
+## .authentication
+
+## .permissions
+
+## .headers
+
+[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
\ No newline at end of file
diff --git a/docs/csrf.md b/docs/csrf.md
deleted file mode 100644
index 8e0b9480..00000000
--- a/docs/csrf.md
+++ /dev/null
@@ -1,4 +0,0 @@
-REST framework and CSRF protection
-==================================
-
-> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability -- very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." - Jeff Atwood
\ No newline at end of file
diff --git a/docs/formoverloading.md b/docs/formoverloading.md
deleted file mode 100644
index cab47db9..00000000
--- a/docs/formoverloading.md
+++ /dev/null
@@ -1,46 +0,0 @@
-Supporting browser-based PUT & DELETE
-=====================================
-
-> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE" - [RESTful Web Services](1), Leonard Richardson & Sam Ruby.
-
-This is the same strategy as is used in [Ruby on Rails](2).
-
-Overloading the HTTP method
----------------------------
-
-For example, given the following form:
-
-
-
-`request.method` would return `"DELETE"`.
-
-Overloading the HTTP content type
----------------------------------
-
-Browser-based submission of content types other than form are supported by using form fields named `_content` and `_content_type`:
-
-For example, given the following form:
-
-
-
-`request.content_type` would return `"application/json"`, and `request.content` would return `"{'count': 1}"`
-
-Why not just use Javascript?
-============================
-
-**[TODO]**
-
-Doesn't HTML5 support PUT and DELETE forms?
-===========================================
-
-Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec](3). There remains [ongoing discussion](4) about adding support for `PUT` and `DELETE`, as well as how to support content-types other than form-encoded data.
-
-[1]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
-[2]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
-[3]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
-[4]: http://amundsen.com/examples/put-delete-forms/
diff --git a/docs/index.md b/docs/index.md
index 9bd90d8d..f309c939 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,10 +1,62 @@
-Quickstart
-==========
+# Django REST framework
+
+**A toolkit for building well-connected, self-describing Web APIs.**
+
+**WARNING: This documentation is for the 2.0 redesign of REST framework. It is a work in progress.**
+
+Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
+
+Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box.
+
+## Requirements
+
+REST framework requires the following:
+
+* Python (2.6, 2.7)
+* Django (1.3, 1.4, 1.5)
+* [URLObject][urlobject] (2.0.0+)
+
+The following packages are optional:
+
+* [Markdown][markdown] (2.1.0+) - Markdown support for the self describing API.
+* [PyYAML][yaml] (3.10+) - YAML content type support.
+
+If you're installing using `pip`, all requirements and optional packages will be installed by default.
+
+## Installation
+
+**WARNING: These instructions will only become valid once this becomes the master version**
+
+Install using `pip`...
+
+ pip install djangorestframework
+
+...or clone the project from github.
+
+ git clone git@github.com:tomchristie/django-rest-framework.git
+ pip install -r requirements.txt
+
+Add `djangorestframework` to your `INSTALLED_APPS`.
+
+ INSTALLED_APPS = (
+ ...
+ 'djangorestframework',
+ )
+
+If you're intending to use the browserable API you'll want to add REST framework's login and logout views. Add the following to your root `urls.py` file.
+
+ urlpatterns = patterns('',
+ ...
+ url(r'^auth', include('djangorestframework.urls', namespace='djangorestframework'))
+ )
+
+## Quickstart
**TODO**
-Tutorial
-========
+## Tutorial
+
+The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
* [1 - Serialization][tut-1]
* [2 - Requests & Responses][tut-2]
@@ -13,8 +65,9 @@ Tutorial
* [5 - Relationships & hyperlinked APIs][tut-5]
* [6 - Resource orientated projects][tut-6]
-API Guide
-=========
+## API Guide
+
+The API guide is your complete reference manual to all the functionality provided by REST framework.
* [Requests][request]
* [Responses][response]
@@ -24,21 +77,45 @@ API Guide
* [Serializers][serializers]
* [Authentication][authentication]
* [Permissions][permissions]
+* [Exceptions][exceptions]
* [Status codes][status]
+* [Returning URLs][urls]
-Topics
-======
+## Topics
+
+General guides to using REST framework.
-* [Returning URLs][urls]
* [CSRF][csrf]
* [Form overloading][formoverloading]
-Other
-=====
+## License
+
+Copyright (c) 2011-2012, Tom Christie
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
-* Why REST framework
-* Contributing
-* Change Log
+Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice, this
+list of conditions and the following disclaimer in the documentation and/or
+other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+[urlobject]: https://github.com/zacharyvoase/urlobject
+[markdown]: http://pypi.python.org/pypi/Markdown/
+[yaml]: http://pypi.python.org/pypi/PyYAML
[tut-1]: tutorial/1-serialization.md
[tut-2]: tutorial/2-requests-and-responses.md
@@ -47,16 +124,17 @@ Other
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
[tut-6]: tutorial/6-resource-orientated-projects.md
-[request]: request.md
-[response]: response.md
-[views]: views.md
-[parsers]: parsers.md
-[renderers]: renderers.md
-[serializers]: serializers.md
-[authentication]: authentication.md
-[permissions]: permissions.md
-[status]: status.md
-
-[urls]: urls.md
-[csrf]: csrf.md
-[formoverloading]: formoverloading.md
+[request]: api-guide/requests.md
+[response]: api-guide/responses.md
+[views]: api-guide/views.md
+[parsers]: api-guide/parsers.md
+[renderers]: api-guide/renderers.md
+[serializers]: api-guide/serializers.md
+[authentication]: api-guide/authentication.md
+[permissions]: api-guide/permissions.md
+[exceptions]: api-guide/exceptions.md
+[status]: api-guide/status.md
+[urls]: api-guide/urls.md
+
+[csrf]: topics/csrf.md
+[formoverloading]: topics/formoverloading.md
diff --git a/docs/mkdocs.py b/docs/mkdocs.py
new file mode 100755
index 00000000..f984e6f9
--- /dev/null
+++ b/docs/mkdocs.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python
+
+import markdown
+import os
+import re
+
+root = os.path.dirname(__file__)
+local = True
+
+if local:
+ base_url = 'file://%s/html/' % os.path.normpath(os.path.join(os.getcwd(), root))
+ suffix = '.html'
+ index = 'index.html'
+else:
+ base_url = 'http://tomchristie.github.com/restframeworkdocs/'
+ suffix = ''
+ index = ''
+
+
+main_header = '
'
+
+page = open(os.path.join(root, 'template.html'), 'r').read()
+
+for (dirpath, dirnames, filenames) in os.walk(root):
+ for filename in filenames:
+ if not filename.endswith('.md'):
+ continue
+
+ toc = ''
+ text = open(os.path.join(dirpath, filename), 'r').read().decode('utf-8')
+ for line in text.splitlines():
+ if line.startswith('# '):
+ title = line[2:].strip()
+ template = main_header
+ elif line.startswith('## '):
+ title = line[3:].strip()
+ template = sub_header
+ else:
+ continue
+
+ anchor = title.lower().replace(' ', '-').replace(':-', '-').replace("'", '').replace('?', '').replace('.', '')
+ template = template.replace('{{ title }}', title)
+ template = template.replace('{{ anchor }}', anchor)
+ toc += template + '\n'
+
+ content = markdown.markdown(text, ['headerid'])
+
+ build_dir = os.path.join(root, 'html', dirpath)
+ build_file = os.path.join(build_dir, filename[:-3] + '.html')
+
+ if not os.path.exists(build_dir):
+ os.makedirs(build_dir)
+ output = page.replace('{{ content }}', content).replace('{{ toc }}', toc).replace('{{ base_url }}', base_url).replace('{{ suffix }}', suffix).replace('{{ index }}', index)
+ output = re.sub(r'a href="([^"]*)\.md"', r'a href="\1.html"', output)
+ open(build_file, 'w').write(output.encode('utf-8'))
diff --git a/docs/parsers.md b/docs/parsers.md
deleted file mode 100644
index 44e33105..00000000
--- a/docs/parsers.md
+++ /dev/null
@@ -1,5 +0,0 @@
-Parsers
-=======
-
-.parse(request)
----------------
diff --git a/docs/renderers.md b/docs/renderers.md
deleted file mode 100644
index 20cdb8ad..00000000
--- a/docs/renderers.md
+++ /dev/null
@@ -1,6 +0,0 @@
-Renderers
-=========
-
-.render(response)
------------------
-
diff --git a/docs/request.md b/docs/request.md
deleted file mode 100644
index b0491897..00000000
--- a/docs/request.md
+++ /dev/null
@@ -1,76 +0,0 @@
-Request
-=======
-
-> If you're doing REST-based web service stuff ... you should ignore request.POST.
->
-> — Malcom Tredinnick, [Django developers group][1]
-
-The `Request` object in `djangorestframework` extends the standard `HttpRequest`, adding support for parsing multiple content types, allowing browser-based `PUT`, `DELETE` and other methods, and adding flexible per-request authentication.
-
-method
-------
-
-`request.method` returns the uppercased string representation of the request's HTTP method.
-
-Browser-based `PUT`, `DELETE` and other requests are supported, and can be made by using a hidden form field named `_method` in a regular `POST` form.
-
-
-
-content_type
-------------
-
-`request.content`, returns a string object representing the mimetype of the HTTP request's body, if one exists.
-
-
-
-DATA
-----
-
-`request.DATA` returns the parsed content of the request body. This is similar to the standard `HttpRequest.POST` attribute except that:
-
-1. It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
-2. It supports parsing multiple content types, rather than just form data. For example you can handle incoming json data in the same way that you handle incoming form data.
-
-FILES
------
-
-`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing that is used for `request.DATA`.
-
-This allows you to support file uploads from multiple content-types. For example you can write a parser that supports `POST`ing the raw content of a file, instead of using form-encoded file uploads.
-
-user
-----
-
-`request.user` returns a `django.contrib.auth.models.User` instance.
-
-auth
-----
-
-`request.auth` returns any additional authentication context that may not be contained in `request.user`. The exact behavior of `request.auth` depends on what authentication has been set in `request.authentication`. For many types of authentication this will simply be `None`, but it may also be an object representing a permission scope, an expiry time, or any other information that might be contained in a token-based authentication scheme.
-
-parsers
--------
-
-`request.parsers` should be set to a list of `Parser` instances that can be used to parse the content of the request body.
-
-`request.parsers` may no longer be altered once `request.DATA`, `request.FILES` or `request.POST` have been accessed.
-
-If you're using the `djangorestframework.views.View` class... **[TODO]**
-
-stream
-------
-
-`request.stream` returns a stream representing the content of the request body.
-
-You will not typically need to access `request.stream`, unless you're writing a `Parser` class.
-
-authentication
---------------
-
-`request.authentication` should be set to a list of `Authentication` instances that can be used to authenticate the request.
-
-`request.authentication` may no longer be altered once `request.user` or `request.auth` have been accessed.
-
-If you're using the `djangorestframework.views.View` class... **[TODO]**
-
-[1]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
\ No newline at end of file
diff --git a/docs/response.md b/docs/response.md
deleted file mode 100644
index d77c9a0d..00000000
--- a/docs/response.md
+++ /dev/null
@@ -1,27 +0,0 @@
-Responses
-=========
-
-> HTTP has provisions for several mechanisms for "content negotiation" -- the process of selecting the best representation for a given response when there are multiple representations available. -- RFC 2616, Fielding et al.
-
-> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. -- Django documentation.
-
-Django REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
-
-The `Response` class subclasses Django's `TemplateResponse`. It works by allowing you to specify a serializer and a number of different renderers. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
-
-There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it does provide a better interface for returning Web API responses.
-
-Response(content, status, headers=None, serializer=None, renderers=None, format=None)
--------------------------------------------------------------------------------------
-
-serializer
-----------
-
-renderers
----------
-
-view
-----
-
-ImmediateResponse(...)
-----------------------
\ No newline at end of file
diff --git a/docs/serializers.md b/docs/serializers.md
deleted file mode 100644
index 23e37f40..00000000
--- a/docs/serializers.md
+++ /dev/null
@@ -1,47 +0,0 @@
-Serializers
-===========
-
-> 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.
- - Russell Keith-Magee, [Django users group][1]
-
-Serializers provide a way of filtering the content of responses, prior to the response being rendered.
-
-They also allow us to use complex data such as querysets and model instances for the content of our responses, and convert that data into native python datatypes that can then be easily rendered into `JSON`, `XML` or whatever.
-
-REST framework includes a default `Serializer` class which gives you a powerful, generic way to control the output of your responses, but you can also write custom serializers for your data, or create other generic serialization strategies to suit the needs of your API.
-
-BaseSerializer
---------------
-
-This is the base class for all serializers. If you want to provide your own custom serialization, override this class.
-
-.serialize()
-------------
-
-Serializer
-----------
-
-This is the default serializer.
-
-fields
-------
-
-include
--------
-
-exclude
--------
-
-rename
-------
-
-related_serializer
-------------------
-
-depth
------
-
-[1]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
diff --git a/docs/status.md b/docs/status.md
deleted file mode 100644
index ca866cad..00000000
--- a/docs/status.md
+++ /dev/null
@@ -1,17 +0,0 @@
-Status Codes
-============
-
-> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
- - RFC 2324
-
-REST framework provides a ...
-These are simply ...
-
- from djangorestframework import status
-
- def view(self):
- return Response(status=status.HTTP_404_NOT_FOUND)
-
-For more information see [RFC 2616](1).
-
-[1]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
\ No newline at end of file
diff --git a/docs/template.html b/docs/template.html
new file mode 100644
index 00000000..a8a0d741
--- /dev/null
+++ b/docs/template.html
@@ -0,0 +1,150 @@
+
+
+
+ Django REST framework
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/topics/csrf.md b/docs/topics/csrf.md
new file mode 100644
index 00000000..a2ee1b9c
--- /dev/null
+++ b/docs/topics/csrf.md
@@ -0,0 +1,12 @@
+# Working with AJAX and CSRF
+
+> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability -- very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
+>
+> — [Jeff Atwood][cite]
+
+* Explain need to add CSRF token to AJAX requests.
+* Explain defered CSRF style used by REST framework
+* Why you should use Django's standard login/logout views, and not REST framework view
+
+
+[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
\ No newline at end of file
diff --git a/docs/topics/formoverloading.md b/docs/topics/formoverloading.md
new file mode 100644
index 00000000..a1828c3b
--- /dev/null
+++ b/docs/topics/formoverloading.md
@@ -0,0 +1,43 @@
+# Browser based PUT & DELETE
+
+> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"
+>
+> — [RESTful Web Services](1), Leonard Richardson & Sam Ruby.
+
+## Overloading the HTTP method
+
+**TODO: Preamble.** Note that this is the same strategy as is used in [Ruby on Rails](2).
+
+For example, given the following form:
+
+
+
+`request.method` would return `"DELETE"`.
+
+## Overloading the HTTP content type
+
+Browser-based submission of content types other than form are supported by using form fields named `_content` and `_content_type`:
+
+For example, given the following form:
+
+
+
+`request.content_type` would return `"application/json"`, and `request.content` would return `"{'count': 1}"`
+
+## Why not just use Javascript?
+
+**[TODO]**
+
+## Doesn't HTML5 support PUT and DELETE forms?
+
+Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec](3). There remains [ongoing discussion](4) about adding support for `PUT` and `DELETE`, as well as how to support content-types other than form-encoded data.
+
+[1]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
+[2]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
+[3]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
+[4]: http://amundsen.com/examples/put-delete-forms/
diff --git a/docs/urls.md b/docs/urls.md
deleted file mode 100644
index 1828dd68..00000000
--- a/docs/urls.md
+++ /dev/null
@@ -1,42 +0,0 @@
-Returning URIs from your Web APIs
-=================================
-
-> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
-> -- Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures.
-
-As a rule, it's probably better practice to return absolute URIs from you web APIs, eg. "http://example.com/foobar", rather than returning relative URIs, eg. "/foobar".
-
-The advantages of doing so are:
-
-* It's more explicit.
-* It leaves less work for your API clients.
-* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
-* It allows use to easily do things like markup HTML representations with hyperlinks.
-
-Django REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
-
-There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
-
-reverse(viewname, request, ...)
--------------------------------
-
-Has the same behavior as [`django.core.urlresolvers.reverse`](1), except that it returns a fully qualified URL, using the request to determine the host and port.
-
- from djangorestframework.utils import reverse
- from djangorestframework.views import View
-
- class MyView(View):
- def get(self, request):
- context = {
- ...
- 'url': reverse('year-summary', request, args=[1945])
- }
- return Response(context)
-
-reverse_lazy(viewname, request, ...)
-------------------------------------
-
-Has the same behavior as [`django.core.urlresolvers.reverse_lazy`](2), except that it returns a fully qualified URL, using the request to determine the host and port.
-
-[1]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
-[1]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
\ No newline at end of file
diff --git a/docs/views.md b/docs/views.md
deleted file mode 100644
index d227339e..00000000
--- a/docs/views.md
+++ /dev/null
@@ -1,43 +0,0 @@
-Views
-=====
-
-REST framework provides a simple `View` class, built on Django's `django.generics.views.View`. The `View` class ensures five main things:
-
-1. Any requests inside the view will become `Request` instances.
-2. `Request` instances will have their `renderers` and `authentication` attributes automatically set.
-3. `Response` instances will have their `parsers` and `serializer` attributes automatically set.
-4. `ImmediateResponse` exceptions will be caught and returned as regular responses.
-5. Any permissions provided will be checked prior to passing the request to a handler method.
-
-Additionally there are a some minor extras, such as providing a default `options` handler, setting some common headers on the response prior to return, and providing the useful `initial()` and `final()` hooks.
-
-View
-----
-
-.get(), .post(), .put(), .delete() etc...
------------------------------------------
-
-.initial(request, *args, **kwargs)
-----------------------------------
-
-.final(request, response, *args, **kwargs)
-------------------------------------------
-
-.parsers
---------
-
-.renderers
-----------
-
-.serializer
------------
-
-.authentication
----------------
-
-.permissions
-------------
-
-.headers
---------
-
--
cgit v1.2.3
From 99415564741ca849c0771a3cdd3c18a72b74a373 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 1 Sep 2012 21:23:50 +0100
Subject: Get docs ready to deploy
---
docs/index.md | 2 +
docs/mkdocs.py | 56 -
docs/static/css/bootstrap-responsive.css | 1040 ++++++
docs/static/css/bootstrap.css | 5624 ++++++++++++++++++++++++++++++
docs/static/js/bootstrap-alert.js | 90 +
docs/static/js/bootstrap-button.js | 96 +
docs/static/js/bootstrap-carousel.js | 176 +
docs/static/js/bootstrap-collapse.js | 158 +
docs/static/js/bootstrap-dropdown.js | 150 +
docs/static/js/bootstrap-modal.js | 239 ++
docs/static/js/bootstrap-popover.js | 103 +
docs/static/js/bootstrap-scrollspy.js | 151 +
docs/static/js/bootstrap-tab.js | 135 +
docs/static/js/bootstrap-tooltip.js | 275 ++
docs/static/js/bootstrap-transition.js | 60 +
docs/static/js/bootstrap-typeahead.js | 300 ++
docs/static/js/jquery.js | 4 +
docs/topics/credits.md | 53 +
18 files changed, 8656 insertions(+), 56 deletions(-)
delete mode 100755 docs/mkdocs.py
create mode 100644 docs/static/css/bootstrap-responsive.css
create mode 100644 docs/static/css/bootstrap.css
create mode 100644 docs/static/js/bootstrap-alert.js
create mode 100644 docs/static/js/bootstrap-button.js
create mode 100644 docs/static/js/bootstrap-carousel.js
create mode 100644 docs/static/js/bootstrap-collapse.js
create mode 100644 docs/static/js/bootstrap-dropdown.js
create mode 100644 docs/static/js/bootstrap-modal.js
create mode 100644 docs/static/js/bootstrap-popover.js
create mode 100644 docs/static/js/bootstrap-scrollspy.js
create mode 100644 docs/static/js/bootstrap-tab.js
create mode 100644 docs/static/js/bootstrap-tooltip.js
create mode 100644 docs/static/js/bootstrap-transition.js
create mode 100644 docs/static/js/bootstrap-typeahead.js
create mode 100644 docs/static/js/jquery.js
create mode 100644 docs/topics/credits.md
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index f309c939..340c6734 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -87,6 +87,7 @@ General guides to using REST framework.
* [CSRF][csrf]
* [Form overloading][formoverloading]
+* [Credits][credits]
## License
@@ -138,3 +139,4 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[csrf]: topics/csrf.md
[formoverloading]: topics/formoverloading.md
+[credits]: topics/credits.md
diff --git a/docs/mkdocs.py b/docs/mkdocs.py
deleted file mode 100755
index f984e6f9..00000000
--- a/docs/mkdocs.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env python
-
-import markdown
-import os
-import re
-
-root = os.path.dirname(__file__)
-local = True
-
-if local:
- base_url = 'file://%s/html/' % os.path.normpath(os.path.join(os.getcwd(), root))
- suffix = '.html'
- index = 'index.html'
-else:
- base_url = 'http://tomchristie.github.com/restframeworkdocs/'
- suffix = ''
- index = ''
-
-
-main_header = '
"&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/
+
--
cgit v1.2.3
From 36cd91bbbe6bc0aeef9b1eb711415988f5c4e501 Mon Sep 17 00:00:00 2001
From: Mjumbe Wawatu Poe
Date: Fri, 7 Sep 2012 14:12:46 -0400
Subject: Update docs for tokenauth
---
docs/api-guide/authentication.md | 20 ++++++++++++--------
1 file changed, 12 insertions(+), 8 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index ed7ac288..c5e4c1cc 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -8,7 +8,7 @@ Authentication will run the first time either the `request.user` or `request.aut
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
-The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
+The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
## How authentication is determined
@@ -36,7 +36,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi
def get(self, request, format=None):
content = {
- 'user': unicode(request.user), # `django.contrib.auth.User` instance.
+ 'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
@@ -49,7 +49,7 @@ Or, if you're using the `@api_view` decorator with function based views.
)
def example_view(request, format=None):
content = {
- 'user': unicode(request.user), # `django.contrib.auth.User` instance.
+ 'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
@@ -65,16 +65,20 @@ If successfully authenticated, `UserBasicAuthentication` provides the following
* `request.user` will be a `django.contrib.auth.models.User` instance.
* `request.auth` will be `None`.
-## TokenBasicAuthentication
+## TokenAuthentication
-This policy uses [HTTP Basic Authentication][basicauth], signed against a token key and secret. Token basic authentication is appropriate for client-server setups, such as native desktop and mobile clients.
+This policy uses [HTTP Authentication][basicauth] with a custom authentication scheme called "Token". Token basic authentication is appropriate for client-server setups, such as native desktop and mobile clients. The token key should be passed in as a string to the "Authorization" HTTP header. For example:
-**Note:** If you run `TokenBasicAuthentication` in production your API must be `https` only, or it will be completely insecure.
+ curl http://my.api.org/ -X POST -H "Authorization: Token 0123456789abcdef0123456789abcdef"
-If successfully authenticated, `TokenBasicAuthentication` provides the following credentials.
+**Note:** If you run `TokenAuthentication` in production your API must be `https` only, or it will be completely insecure.
+
+If successfully authenticated, `TokenAuthentication` provides the following credentials.
* `request.user` will be a `django.contrib.auth.models.User` instance.
-* `request.auth` will be a `djangorestframework.models.BasicToken` instance.
+* `request.auth` will be a `djangorestframework.tokenauth.models.Token` instance.
+
+To use the `TokenAuthentication` scheme, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications. To use your own token model, subclass the `djangorestframework.tokenauth.authentication.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. For convenience, the `djangorestframework.tokenauth.models.BaseToken` abstract model implements this minimum contract, and also randomly populates the key field when none is provided.
## OAuthAuthentication
--
cgit v1.2.3
From 3b1404bd7d37d8c60cf45071852f86eea8d4c68f Mon Sep 17 00:00:00 2001
From: Mjumbe Wawatu Poe
Date: Fri, 7 Sep 2012 14:23:53 -0400
Subject: Rename the default token class to "BasicToken"
---
docs/api-guide/authentication.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index c5e4c1cc..c5b7ac9c 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -76,7 +76,7 @@ This policy uses [HTTP Authentication][basicauth] with a custom authentication s
If successfully authenticated, `TokenAuthentication` provides the following credentials.
* `request.user` will be a `django.contrib.auth.models.User` instance.
-* `request.auth` will be a `djangorestframework.tokenauth.models.Token` instance.
+* `request.auth` will be a `djangorestframework.tokenauth.models.BasicToken` instance.
To use the `TokenAuthentication` scheme, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications. To use your own token model, subclass the `djangorestframework.tokenauth.authentication.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. For convenience, the `djangorestframework.tokenauth.models.BaseToken` abstract model implements this minimum contract, and also randomly populates the key field when none is provided.
--
cgit v1.2.3
From f95f96aba7c7f1ea26af09b9e768d5c8997bac98 Mon Sep 17 00:00:00 2001
From: Alec Perkins
Date: Fri, 7 Sep 2012 14:31:24 -0400
Subject: [docs] Fix typo, add link to Tom's Twitter profile
---
docs/tutorial/3-class-based-views.md | 2 +-
docs/tutorial/6-resource-orientated-projects.md | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index b3000ad9..d5ba045e 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -7,7 +7,7 @@ We can also write our API views using class based views, rather than function ba
We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.
from blog.models import Comment
- from blog.serializers import ComentSerializer
+ from blog.serializers import CommentSerializer
from django.http import Http404
from djangorestframework.views import APIView
from djangorestframework.response import Response
diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md
index ce51cce5..4282c25d 100644
--- a/docs/tutorial/6-resource-orientated-projects.md
+++ b/docs/tutorial/6-resource-orientated-projects.md
@@ -44,6 +44,6 @@ We've reached the end of our tutorial. If you want to get more involved in the
* Contribute on GitHub by reviewing issues, and submitting issues or pull requests.
* Join the REST framework group, and help build the community.
-* Follow me on Twitter and say hi.
+* Follow me [on Twitter](https://twitter.com/_tomchristie) and say hi.
Now go build something great.
\ No newline at end of file
--
cgit v1.2.3
From f741cdae44bc455089a5ed7e1dbea4760ca97b85 Mon Sep 17 00:00:00 2001
From: Mjumbe Wawatu Poe
Date: Fri, 7 Sep 2012 16:12:33 -0400
Subject: Move TokenAuthentication class into
djangorestframework.authentication
---
docs/api-guide/authentication.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index c5b7ac9c..5f176d02 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -67,9 +67,9 @@ If successfully authenticated, `UserBasicAuthentication` provides the following
## TokenAuthentication
-This policy uses [HTTP Authentication][basicauth] with a custom authentication scheme called "Token". Token basic authentication is appropriate for client-server setups, such as native desktop and mobile clients. The token key should be passed in as a string to the "Authorization" HTTP header. For example:
+This policy uses [HTTP Authentication][basicauth] with no authentication scheme. Token basic authentication is appropriate for client-server setups, such as native desktop and mobile clients. The token key should be passed in as a string to the "Authorization" HTTP header. For example:
- curl http://my.api.org/ -X POST -H "Authorization: Token 0123456789abcdef0123456789abcdef"
+ curl http://my.api.org/ -X POST -H "Authorization: 0123456789abcdef0123456789abcdef"
**Note:** If you run `TokenAuthentication` in production your API must be `https` only, or it will be completely insecure.
@@ -78,7 +78,7 @@ If successfully authenticated, `TokenAuthentication` provides the following cred
* `request.user` will be a `django.contrib.auth.models.User` instance.
* `request.auth` will be a `djangorestframework.tokenauth.models.BasicToken` instance.
-To use the `TokenAuthentication` scheme, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications. To use your own token model, subclass the `djangorestframework.tokenauth.authentication.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. For convenience, the `djangorestframework.tokenauth.models.BaseToken` abstract model implements this minimum contract, and also randomly populates the key field when none is provided.
+To use the `TokenAuthentication` policy, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications and sync your database. To use your own token model, subclass the `djangorestframework.tokenauth.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. For convenience, the `djangorestframework.tokenauth.models.BaseToken` abstract model implements this minimum contract, and also randomly populates the key field when none is provided.
## OAuthAuthentication
--
cgit v1.2.3
From 8df71f4d1d9a8a3df8e053d99340fbe5bf78b8ad Mon Sep 17 00:00:00 2001
From: Mjumbe Wawatu Poe
Date: Fri, 7 Sep 2012 16:19:15 -0400
Subject: Get rid of the BaseToken abstract model
---
docs/api-guide/authentication.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 5f176d02..45da2c55 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -78,7 +78,7 @@ If successfully authenticated, `TokenAuthentication` provides the following cred
* `request.user` will be a `django.contrib.auth.models.User` instance.
* `request.auth` will be a `djangorestframework.tokenauth.models.BasicToken` instance.
-To use the `TokenAuthentication` policy, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications and sync your database. To use your own token model, subclass the `djangorestframework.tokenauth.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. For convenience, the `djangorestframework.tokenauth.models.BaseToken` abstract model implements this minimum contract, and also randomly populates the key field when none is provided.
+To use the `TokenAuthentication` policy, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications and sync your database. To use your own token model, subclass the `djangorestframework.tokenauth.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. Refer to the `djangorestframework.tokenauth.models.BasicToken` model as an example.
## OAuthAuthentication
--
cgit v1.2.3
From 8ee763739d66bbaaa9c0f78fa05bbc17dce3de13 Mon Sep 17 00:00:00 2001
From: Marko Tibold
Date: Fri, 7 Sep 2012 22:53:02 +0200
Subject: Add some missing imports. Fix some typos. Fix some indentation
errors.
---
docs/tutorial/3-class-based-views.md | 27 ++++++++++++++-------------
1 file changed, 14 insertions(+), 13 deletions(-)
(limited to 'docs')
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index b3000ad9..24785179 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -7,30 +7,31 @@ We can also write our API views using class based views, rather than function ba
We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.
from blog.models import Comment
- from blog.serializers import ComentSerializer
+ from blog.serializers import CommentSerializer
from django.http import Http404
from djangorestframework.views import APIView
from djangorestframework.response import Response
- from djangorestframework.status import status
+ from djangorestframework import status
+
class CommentRoot(APIView):
"""
List all comments, or create a new comment.
- """
+ """
def get(self, request, format=None):
comments = Comment.objects.all()
- serializer = ComentSerializer(instance=comments)
+ serializer = CommentSerializer(instance=comments)
return Response(serializer.data)
- def post(self, request, format=None)
- serializer = ComentSerializer(request.DATA)
+ def post(self, request, format=None):
+ serializer = CommentSerializer(request.DATA)
if serializer.is_valid():
comment = serializer.object
comment.save()
- return Response(serializer.serialized, status=HTTP_201_CREATED)
- return Response(serializer.serialized_errors, status=HTTP_400_BAD_REQUEST)
+ return Response(serializer.serialized, status=status.HTTP_201_CREATED)
+ return Response(serializer.serialized_errors, status=status.HTTP_400_BAD_REQUEST)
- comment_root = CommentRoot.as_view()
+ comment_root = CommentRoot.as_view()
So far, so good. It looks pretty similar to the previous case, but we've got better seperation between the different HTTP methods. We'll also need to update the instance view.
@@ -38,18 +39,18 @@ So far, so good. It looks pretty similar to the previous case, but we've got be
"""
Retrieve, update or delete a comment instance.
"""
-
+
def get_object(self, pk):
try:
return Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
raise Http404
-
+
def get(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(instance=comment)
return Response(serializer.data)
-
+
def put(self, request, pk, format=None):
comment = self.get_object(pk)
serializer = CommentSerializer(request.DATA, instance=comment)
@@ -64,7 +65,7 @@ So far, so good. It looks pretty similar to the previous case, but we've got be
comment.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
- comment_instance = CommentInstance.as_view()
+ comment_instance = CommentInstance.as_view()
That's looking good. Again, it's still pretty similar to the function based view right now.
Okay, we're done. If you run the development server everything should be working just as before.
--
cgit v1.2.3
From 79144919f6194cfb60c2828adce98c0f696b5189 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Sep 2012 08:38:14 +0100
Subject: Added @alecperkins.
---
docs/topics/credits.md | 1 +
1 file changed, 1 insertion(+)
(limited to 'docs')
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index f85b80d2..756008a4 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -39,6 +39,7 @@ The following people have helped make REST framework great.
* Daniel Izquierdo
* Can Yavuz
* Shawn Lewis
+* Alec Perkins
Many thanks to everyone who's contributed to the project.
--
cgit v1.2.3
From 382b277dfc74f337d4d74ab100aec031041e42b7 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Sep 2012 08:41:31 +0100
Subject: Link to github accounts in credits
---
docs/topics/credits.md | 118 ++++++++++++++++++++++++++++++++-----------------
1 file changed, 78 insertions(+), 40 deletions(-)
(limited to 'docs')
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index 756008a4..c20f5246 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -2,44 +2,44 @@
The following people have helped make REST framework great.
-* Tom Christie
-* Marko Tibold
-* Paul Bagwell
-* Sébastien Piquemal
-* Carmen Wick
-* Alex Ehlke
-* Alen Mujezinovic
-* Carles Barrobés
-* Michael Fötsch
-* David Larlet
-* Andrew Straw
-* Zeth
-* Fernando Zunino
-* Jens Alm
-* Craig Blaszczyk
-* Garcia Solero
-* Tom Drummond
-* Danilo Bargen
-* Andrew McCloud
-* Thomas Steinacher
-* Meurig Freeman
-* Anthony Nemitz
-* Ewoud Kohl van Wijngaarden
-* Michael Ding
-* Mjumbe Poe
-* Natim
-* Sebastian Żurek
-* Benoit C
-* Chris Pickett
-* Ben Timby
-* Michele Lazzeri
-* Camille Harang
-* Paul Oswald
-* Sean C. Farley
-* Daniel Izquierdo
-* Can Yavuz
-* Shawn Lewis
-* Alec Perkins
+* Tom Christie - [tomchristie]
+* Marko Tibold - [markotibold]
+* Paul Bagwell - [pbgwl]
+* Sébastien Piquemal - [sebpiq]
+* Carmen Wick - [cwick]
+* Alex Ehlke - [aehlke]
+* Alen Mujezinovic - [flashingpumpkin]
+* Carles Barrobés - [txels]
+* Michael Fötsch - [mfoetsch]
+* David Larlet - [david]
+* Andrew Straw - [astraw]
+* Zeth - [zeth]
+* Fernando Zunino - [fzunino]
+* Jens Alm - [ulmus]
+* Craig Blaszczyk - [jakul]
+* Garcia Solero - [garciasolero]
+* Tom Drummond - [devioustree]
+* Danilo Bargen - [gwrtheyrn]
+* Andrew McCloud - [amccloud]
+* Thomas Steinacher - [thomasst]
+* Meurig Freeman - [meurig]
+* Anthony Nemitz - [anemitz]
+* Ewoud Kohl van Wijngaarden - [ekohl]
+* Michael Ding - [yandy]
+* Mjumbe Poe - [mjumbewu]
+* Natim - [natim]
+* Sebastian Żurek - [sebzur]
+* Benoit C - [dzen]
+* Chris Pickett - [bunchesofdonald]
+* Ben Timby - [btimby]
+* Michele Lazzeri - [michelelazzeri-nextage]
+* Camille Harang - [mammique]
+* Paul Oswald - [poswald]
+* Sean C. Farley - [scfarley]
+* Daniel Izquierdo - [izquierdo]
+* Can Yavuz - [tschan]
+* Shawn Lewis - [shawnlewis]
+* Alec Perkins - [alecperkins]
Many thanks to everyone who's contributed to the project.
@@ -56,11 +56,49 @@ Continuous integration testing is managed with [Travis CI][travis-ci].
To contact the author directly:
* twitter: [@_tomchristie][twitter]
-* mail: [tom@tomchristie.com][email]
+* email: [tom@tomchristie.com][email]
[email]: mailto:tom@tomchristie.com
[twitter]: http://twitter.com/_tomchristie
[bootstrap]: http://twitter.github.com/bootstrap/
[markdown]: http://daringfireball.net/projects/markdown/
[github]: github.com/tomchristie/django-rest-framework
-[travis-ci]: https://secure.travis-ci.org/tomchristie/django-rest-framework
\ No newline at end of file
+[travis-ci]: https://secure.travis-ci.org/tomchristie/django-rest-framework
+[tomchristie]: https://github.com/tomchristie
+[markotibold]: https://github.com/markotibold
+[pbgwl]: https://github.com/pbgwl
+[sebpiq]: https://github.com/sebpiq
+[cwick]: https://github.com/cwick
+[aehlke]: https://github.com/aehlke
+[flashingpumpkin]: https://github.com/flashingpumpkin
+[txels]: https://github.com/txels
+[mfoetsch]: https://github.com/mfoetsch
+[david]: https://github.com/david
+[astraw]: https://github.com/astraw
+[zeth]: https://github.com/zeth
+[fzunino]: https://github.com/fzunino
+[ulmus]: https://github.com/ulmus
+[jakul]: https://github.com/jakul
+[garciasolero]: https://github.com/garciasolero
+[devioustree]: https://github.com/devioustree
+[gwrtheyrn]: https://github.com/gwrtheyrn
+[amccloud]: https://github.com/amccloud
+[thomasst]: https://github.com/thomasst
+[meurig]: https://github.com/meurig
+[anemitz]: https://github.com/anemitz
+[ekohl]: https://github.com/ekohl
+[yandy]: https://github.com/yandy
+[mjumbewu]: https://github.com/mjumbewu
+[natim]: https://github.com/natim
+[sebzur]: https://github.com/sebzur
+[dzen]: https://github.com/dzen
+[bunchesofdonald]: https://github.com/bunchesofdonald
+[btimby]: https://github.com/btimby
+[michelelazzeri-nextage]: https://github.com/michelelazzeri-nextage
+[mammique]: https://github.com/mammique
+[poswald]: https://github.com/poswald
+[scfarley]: https://github.com/scfarley
+[izquierdo]: https://github.com/izquierdo
+[tschan]: https://github.com/tschan
+[shawnlewis]: https://github.com/shawnlewis
+[alecperkins]: https://github.com/alecperkins
--
cgit v1.2.3
From 5d9dfcd8ae10db37f0cca043d3b9977e27197487 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Sep 2012 20:23:32 +0100
Subject: Code highlighting in docs
---
docs/static/css/drf-styles.css | 3 +++
docs/static/css/prettify.css | 30 ++++++++++++++++++++++++++++++
docs/static/js/prettify.js | 28 ++++++++++++++++++++++++++++
docs/template.html | 4 +++-
docs/tutorial/1-serialization.md | 1 +
5 files changed, 65 insertions(+), 1 deletion(-)
create mode 100644 docs/static/css/prettify.css
create mode 100644 docs/static/js/prettify.js
(limited to 'docs')
diff --git a/docs/static/css/drf-styles.css b/docs/static/css/drf-styles.css
index fcc60532..ecbd415c 100644
--- a/docs/static/css/drf-styles.css
+++ b/docs/static/css/drf-styles.css
@@ -10,6 +10,9 @@ body {
padding-bottom: 40px;
}
+pre {
+ font-size: 12px;
+}
/* Preserve the spacing of the navbar across different screen sizes. */
diff --git a/docs/static/css/prettify.css b/docs/static/css/prettify.css
new file mode 100644
index 00000000..d437aff6
--- /dev/null
+++ b/docs/static/css/prettify.css
@@ -0,0 +1,30 @@
+.com { color: #93a1a1; }
+.lit { color: #195f91; }
+.pun, .opn, .clo { color: #93a1a1; }
+.fun { color: #dc322f; }
+.str, .atv { color: #D14; }
+.kwd, .prettyprint .tag { color: #1e347b; }
+.typ, .atn, .dec, .var { color: teal; }
+.pln { color: #48484c; }
+
+.prettyprint {
+ padding: 8px;
+ background-color: #f7f7f9;
+ border: 1px solid #e1e1e8;
+}
+.prettyprint.linenums {
+ -webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
+ -moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
+ box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
+}
+
+/* Specify class=linenums on a pre to get line numbering */
+ol.linenums {
+ margin: 0 0 0 33px; /* IE indents via margin-left */
+}
+ol.linenums li {
+ padding-left: 12px;
+ color: #bebec5;
+ line-height: 20px;
+ text-shadow: 0 1px 0 #fff;
+}
\ No newline at end of file
diff --git a/docs/static/js/prettify.js b/docs/static/js/prettify.js
new file mode 100644
index 00000000..eef5ad7e
--- /dev/null
+++ b/docs/static/js/prettify.js
@@ -0,0 +1,28 @@
+var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
+(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
+[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
+l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
+q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
+q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
+"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
+a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
+for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
+"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
+H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
+J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
+I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]+/],["dec",/^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^
-
+
@@ -102,6 +103,7 @@
================================================== -->
+
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index 3d6615d9..610d8ed1 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -8,6 +8,7 @@ This tutorial will walk you through the building blocks that make up REST framew
Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on.
+ :::bash
mkdir ~/env
virtualenv --no-site-packages ~/env/tutorial
source ~/env/tutorial/bin/activate
--
cgit v1.2.3
From 247696e820dfe4535b3141d744129d654f9b6aea Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Sep 2012 22:06:13 +0100
Subject: Links to source files in docs
---
docs/api-guide/authentication.md | 2 ++
docs/api-guide/exceptions.md | 2 ++
docs/api-guide/parsers.md | 2 ++
docs/api-guide/permissions.md | 2 ++
docs/api-guide/renderers.md | 2 ++
docs/api-guide/requests.md | 2 ++
docs/api-guide/responses.md | 2 ++
docs/api-guide/reverse.md | 2 ++
docs/api-guide/serializers.md | 2 ++
docs/api-guide/settings.md | 2 ++
docs/api-guide/status-codes.md | 2 ++
docs/api-guide/throttling.md | 2 ++
docs/api-guide/views.md | 2 ++
docs/static/css/drf-styles.css | 12 ++++++++++--
14 files changed, 36 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 45da2c55..ca29bc4d 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -1,3 +1,5 @@
+
+
# Authentication
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
index d41327c6..bb3ed56e 100644
--- a/docs/api-guide/exceptions.md
+++ b/docs/api-guide/exceptions.md
@@ -1,3 +1,5 @@
+
+
# Exceptions
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 2edc11de..5e2344a3 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -1,3 +1,5 @@
+
+
# Parsers
## .parse(request)
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index 8b137891..2e15107c 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -1 +1,3 @@
+
+# Permissions
\ No newline at end of file
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 5a66da69..1cd6d1a0 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -1,3 +1,5 @@
+
+
# Renderers
## .render(response)
diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md
index 67ddfdac..6746bb20 100644
--- a/docs/api-guide/requests.md
+++ b/docs/api-guide/requests.md
@@ -1,3 +1,5 @@
+
+
# Requests
> If you're doing REST-based web service stuff ... you should ignore request.POST.
diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md
index 38f6e8cb..6c279f17 100644
--- a/docs/api-guide/responses.md
+++ b/docs/api-guide/responses.md
@@ -1,3 +1,5 @@
+
+
# Responses
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md
index 5a1d6e26..6e42b68e 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -1,3 +1,5 @@
+
+
# Returning URIs from your Web APIs
> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 377b0c10..38a1e560 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -1,3 +1,5 @@
+
+
# Serializers
> Expanding the usefulness of the serializers is something that we would
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 1411b9ec..ae8dce76 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -1,3 +1,5 @@
+
+
# Settings
Configuration for REST framework is all namespaced inside the `API_SETTINGS` setting.
diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md
index c1d45905..6693c79f 100644
--- a/docs/api-guide/status-codes.md
+++ b/docs/api-guide/status-codes.md
@@ -1,3 +1,5 @@
+
+
# Status Codes
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index 8b137891..e3a66c83 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -1 +1,3 @@
+
+# Throttling
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index dd1dbebe..43924544 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -1,3 +1,5 @@
+
+
> Django's class based views are a welcome departure from the old-style views.
>
> — [Reinout van Rees][cite]
diff --git a/docs/static/css/drf-styles.css b/docs/static/css/drf-styles.css
index ecbd415c..a0566790 100644
--- a/docs/static/css/drf-styles.css
+++ b/docs/static/css/drf-styles.css
@@ -14,6 +14,14 @@ pre {
font-size: 12px;
}
+a.github {
+ float: right;
+ margin-top: -12px;
+}
+
+a.github:hover {
+ text-decoration: none;
+}
/* Preserve the spacing of the navbar across different screen sizes. */
.navbar-inner {
@@ -66,7 +74,7 @@ blockquote {
border-left: none;
}
- blockquote:before {
+blockquote:before {
display: block;
content: "\201C";
font-size: 80px;
@@ -76,7 +84,7 @@ blockquote {
color: #7a7a7a;
}
- blockquote p:last-child {
+blockquote p:last-child {
color: #999999;
font-size: 14px;
display: block;
--
cgit v1.2.3
From b5e07abc15f0937263e183b7800f30b558e37a1b Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Sep 2012 22:13:11 +0100
Subject: Move quote below title for consistency
---
docs/api-guide/views.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 43924544..04647f91 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -1,11 +1,11 @@
+# Views
+
> Django's class based views are a welcome departure from the old-style views.
>
> — [Reinout van Rees][cite]
-# Views
-
REST framework provides a simple `APIView` class, built on Django's `django.generics.views.View`. The `APIView` class ensures five main things:
1. Any requests inside the view will become `Request` instances.
--
cgit v1.2.3
From baa6e2c18b94345e8f00f28a34817abdbdb437dc Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 8 Sep 2012 22:31:44 +0100
Subject: Hide toc overflow
---
docs/static/css/drf-styles.css | 4 ++++
1 file changed, 4 insertions(+)
(limited to 'docs')
diff --git a/docs/static/css/drf-styles.css b/docs/static/css/drf-styles.css
index a0566790..49740aab 100644
--- a/docs/static/css/drf-styles.css
+++ b/docs/static/css/drf-styles.css
@@ -23,6 +23,10 @@ a.github:hover {
text-decoration: none;
}
+#table-of-contents {
+ overflow: hidden;
+}
+
/* Preserve the spacing of the navbar across different screen sizes. */
.navbar-inner {
padding: 5px 0;
--
cgit v1.2.3
From d4f8b4cf0683923fe85652f8fd572d2931eb3074 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 9 Sep 2012 16:56:04 +0100
Subject: Collapsing menu, travis and github badges, horizontal scrolling code
on overflow
---
docs/index.md | 4 ++++
docs/static/css/drf-styles.css | 29 +++++++++++++++++++++++++++++
docs/template.html | 2 +-
3 files changed, 34 insertions(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index 72e247ee..46c5cf19 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,3 +1,6 @@
+
+[][travis]
+
# Django REST framework
**A toolkit for building well-connected, self-describing Web APIs.**
@@ -131,6 +134,7 @@ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=restframework2
[urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML
diff --git a/docs/static/css/drf-styles.css b/docs/static/css/drf-styles.css
index 49740aab..bb31b07c 100644
--- a/docs/static/css/drf-styles.css
+++ b/docs/static/css/drf-styles.css
@@ -23,10 +23,39 @@ a.github:hover {
text-decoration: none;
}
+.dropdown .dropdown-menu {
+ display: none;
+}
+
+.dropdown.open .dropdown-menu {
+ display: block;
+}
+
+body.index #main-content iframe {
+ float: right;
+}
+
+body.index #main-content iframe {
+ float: right;
+ margin-right: -15px;
+}
+
+body.index #main-content p:first-of-type {
+ float: right;
+ margin-right: 8px;
+ margin-top: -1px;
+}
+
#table-of-contents {
overflow: hidden;
}
+pre {
+ overflow: auto;
+ word-wrap: normal;
+ white-space: pre;
+}
+
/* Preserve the spacing of the navbar across different screen sizes. */
.navbar-inner {
padding: 5px 0;
diff --git a/docs/template.html b/docs/template.html
index a4b4d4b4..c8cfbbab 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -16,7 +16,7 @@
-
+
--
cgit v1.2.3
From 60e6bba12b6843b01194b6534fb56129ec0b2140 Mon Sep 17 00:00:00 2001
From: Alec Perkins
Date: Sun, 9 Sep 2012 16:46:05 -0400
Subject: Browsable API doc topic
---
docs/index.md | 2 +
docs/template.html | 1 +
docs/topics/browsable-api.md | 86 +++++++++++++++++++++++++++++++
docs/tutorial/2-requests-and-responses.md | 10 +++-
4 files changed, 97 insertions(+), 2 deletions(-)
create mode 100644 docs/topics/browsable-api.md
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index 46c5cf19..0072b56f 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -94,6 +94,7 @@ General guides to using REST framework.
* [CSRF][csrf]
* [Form overloading][formoverloading]
+* [Working with the Browsable API][browsableapi]
* [Contributing to REST framework][contributing]
* [Credits][credits]
@@ -162,5 +163,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[csrf]: topics/csrf.md
[formoverloading]: topics/formoverloading.md
+[browsableapi]: topics/browsable-api.md
[contributing]: topics/contributing.md
[credits]: topics/credits.md
diff --git a/docs/template.html b/docs/template.html
index c8cfbbab..819e3b92 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -64,6 +64,7 @@
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md
new file mode 100644
index 00000000..6d2d2a37
--- /dev/null
+++ b/docs/topics/browsable-api.md
@@ -0,0 +1,86 @@
+# Working with the Browsable API
+
+API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`.
+
+## URLs
+
+If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `djangorestframework` package includes a [`reverse`](../api-guide/reverse.md) helper for this purpose.
+
+
+## Formats
+
+By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox](https://addons.mozilla.org/en-US/firefox/addon/jsonview/) and [Chrome](https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc).
+
+
+## Customizing
+
+To customize the look-and-feel, create a template called `api.html` and add it to your project, eg: `templates/djangorestframework/api.html`, that extends the `djangorestframework/base.html` template.
+
+The included browsable API template is built with [Bootstrap (2.1.1)](http://getbootstrap.com), making it easy to customize the look-and-feel.
+
+### Theme
+
+To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme.
+
+ {% block bootstrap_theme %}
+
+ {% endblock %}
+
+A suitable replacement theme can be generated using Bootstrap's [Customize Tool](http://twitter.github.com/bootstrap/customize.html#variables). Also, there are pre-made themes available at [Bootswatch](http://bootswatch.com/), which are even hosted by [Bootstrap CDN](http://www.bootstrapcdn.com/). To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
+
+You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
+
+For more specific CSS tweaks, use the `extra_style` block instead.
+
+
+### Blocks
+
+All of the blocks available in the browsable API base template that can be used in your `api.html`.
+
+* `blockbots` - `` tag that blocks crawlers
+* `bodyclass` - (empty) class attribute for the ``
+* `bootstrap_theme` - CSS for the Bootstrap theme
+* `bootstrap_navbar_variant` - CSS class for the navbar
+* `branding` - section of the navbar, see [Bootstrap components](http://twitter.github.com/bootstrap/components.html#navbar)
+* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
+* `extrastyle` - (empty) extra CSS for the page
+* `extrahead` - (empty) extra markup for the page ``
+* `footer` - Any copyright notices or similar footer materials can go here (by default right-aligned)
+* `global_heading` - (empty) Use to insert content below the header but before the breadcrumbs.
+* `title` - title of the page
+* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.
+
+#### Components
+
+All of the [Bootstrap components](http://twitter.github.com/bootstrap/components.html) are available.
+
+##### Tooltips
+
+The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay.
+
+
+### Advanced Customization
+
+#### Context
+
+The context that's available to the template:
+
+* `allowed_methods` : A list of methods allowed by the resource
+* `api_settings` : The API settings
+* `available_formats` : A list of formats allowed by the resource
+* `breadcrumblist` : The list of links following the chain of nested resources
+* `content` : The content of the API response
+* `description` : The description of the resource, generated from its docstring
+* `name` : The name of the resource
+* `post_form` : A form instance for use by the POST form (if allowed)
+* `put_form` : A form instance for use by the PUT form (if allowed)
+* `request` : The request object
+* `response` : The response object
+* `version` : The version of Django REST Framework
+* `view` : The view handling the request
+* `FORMAT_PARAM` : self._FORMAT_QUERY_PARAM
+* `METHOD_PARAM` : getattr(self.view, '_METHOD_PARAM', None)
+
+#### Not using base.html
+
+For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
\ No newline at end of file
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index 89f92c4b..2c11d5ef 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -133,7 +133,12 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][3
**Note: Right now the Browseable API only works with the CBV's. Need to fix that.**
-**TODO: Describe browseable API awesomeness**
+### Browsability
+
+Because the API chooses a return format based on what the client asks for, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a browser. This allows for the API to be easily browsable and usable by humans.
+
+See the [browsable api][4] topic for more information about the browsable API feature and how to customize it.
+
## What's next?
@@ -142,4 +147,5 @@ In [tutorial part 3][4], we'll start using class based views, and see how generi
[json-url]: http://example.com/api/items/4.json
[2]: 1-serialization.md
[3]: http://127.0.0.1:8000/
-[4]: 3-class-based-views.md
\ No newline at end of file
+[4]: ../topics/browsable-api.md
+[5]: 3-class-based-views.md
\ No newline at end of file
--
cgit v1.2.3
From 9684b3fe22d731eb84f67877ab94ee74c8761a01 Mon Sep 17 00:00:00 2001
From: Alec Perkins
Date: Sun, 9 Sep 2012 17:07:54 -0400
Subject: Reference-style links. Much cleaner.
---
docs/topics/browsable-api.md | 25 ++++++++++++++++++-------
1 file changed, 18 insertions(+), 7 deletions(-)
(limited to 'docs')
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md
index 6d2d2a37..ba1984f7 100644
--- a/docs/topics/browsable-api.md
+++ b/docs/topics/browsable-api.md
@@ -4,19 +4,19 @@ API may stand for Application *Programming* Interface, but humans have to be abl
## URLs
-If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `djangorestframework` package includes a [`reverse`](../api-guide/reverse.md) helper for this purpose.
+If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `djangorestframework` package includes a [`reverse`][drfreverse] helper for this purpose.
## Formats
-By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox](https://addons.mozilla.org/en-US/firefox/addon/jsonview/) and [Chrome](https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc).
+By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
## Customizing
To customize the look-and-feel, create a template called `api.html` and add it to your project, eg: `templates/djangorestframework/api.html`, that extends the `djangorestframework/base.html` template.
-The included browsable API template is built with [Bootstrap (2.1.1)](http://getbootstrap.com), making it easy to customize the look-and-feel.
+The included browsable API template is built with [Bootstrap (2.1.1)][bootstrap], making it easy to customize the look-and-feel.
### Theme
@@ -26,7 +26,7 @@ To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html`
{% endblock %}
-A suitable replacement theme can be generated using Bootstrap's [Customize Tool](http://twitter.github.com/bootstrap/customize.html#variables). Also, there are pre-made themes available at [Bootswatch](http://bootswatch.com/), which are even hosted by [Bootstrap CDN](http://www.bootstrapcdn.com/). To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
+A suitable replacement theme can be generated using Bootstrap's [Customize Tool][bcustomize]. Also, there are pre-made themes available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
@@ -41,7 +41,7 @@ All of the blocks available in the browsable API base template that can be used
* `bodyclass` - (empty) class attribute for the ``
* `bootstrap_theme` - CSS for the Bootstrap theme
* `bootstrap_navbar_variant` - CSS class for the navbar
-* `branding` - section of the navbar, see [Bootstrap components](http://twitter.github.com/bootstrap/components.html#navbar)
+* `branding` - section of the navbar, see [Bootstrap components][bcomponentsnav]
* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
* `extrastyle` - (empty) extra CSS for the page
* `extrahead` - (empty) extra markup for the page ``
@@ -52,7 +52,7 @@ All of the blocks available in the browsable API base template that can be used
#### Components
-All of the [Bootstrap components](http://twitter.github.com/bootstrap/components.html) are available.
+All of the [Bootstrap components][bcomponents] are available.
##### Tooltips
@@ -83,4 +83,15 @@ The context that's available to the template:
#### Not using base.html
-For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
\ No newline at end of file
+For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
+
+
+[drfreverse]: ../api-guide/reverse.md
+[ffjsonview]: https://addons.mozilla.org/en-US/firefox/addon/jsonview/
+[chromejsonview]: https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc
+[bootstrap]: http://getbootstrap.com
+[bcustomize]: http://twitter.github.com/bootstrap/customize.html#variables
+[bswatch]: http://bootswatch.com/
+[bcomponents]: http://twitter.github.com/bootstrap/components.html
+[bcomponentsnav]: http://twitter.github.com/bootstrap/components.html#navbar
+
--
cgit v1.2.3
From 4cbc53a75d2d30d05f202777d4e1626011c2cb2e Mon Sep 17 00:00:00 2001
From: Alec Perkins
Date: Sun, 9 Sep 2012 17:25:34 -0400
Subject: Whoops, forgot to explain these.
---
docs/topics/browsable-api.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md
index ba1984f7..6f8920bb 100644
--- a/docs/topics/browsable-api.md
+++ b/docs/topics/browsable-api.md
@@ -78,8 +78,8 @@ The context that's available to the template:
* `response` : The response object
* `version` : The version of Django REST Framework
* `view` : The view handling the request
-* `FORMAT_PARAM` : self._FORMAT_QUERY_PARAM
-* `METHOD_PARAM` : getattr(self.view, '_METHOD_PARAM', None)
+* `FORMAT_PARAM` : The view can accept a format override
+* `METHOD_PARAM` : The view can accept a method override
#### Not using base.html
--
cgit v1.2.3
From c85f799ade0710dd27838e8bfc78989c80213d6a Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 12 Sep 2012 10:12:13 +0100
Subject: Updating docs
---
docs/api-guide/authentication.md | 15 ++++--
docs/api-guide/content-negotiation.md | 7 +++
docs/api-guide/contentnegotiation.md | 1 -
docs/api-guide/exceptions.md | 79 ++++++++++++++++++++++++++++++++
docs/api-guide/format-suffixes.md | 11 +++++
docs/api-guide/generic-views.md | 10 ++++
docs/api-guide/permissions.md | 86 ++++++++++++++++++++++++++++++++++-
docs/api-guide/reverse.md | 4 +-
docs/api-guide/settings.md | 10 +++-
docs/api-guide/throttling.md | 12 +++++
docs/index.md | 10 +++-
docs/static/css/drf-styles.css | 37 +++++++--------
docs/template.html | 9 +++-
13 files changed, 260 insertions(+), 31 deletions(-)
create mode 100644 docs/api-guide/content-negotiation.md
delete mode 100644 docs/api-guide/contentnegotiation.md
create mode 100644 docs/api-guide/format-suffixes.md
create mode 100644 docs/api-guide/generic-views.md
(limited to 'docs')
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index ca29bc4d..f2878f19 100644
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -2,6 +2,10 @@
# Authentication
+> Auth needs to be pluggable.
+>
+> — Jacob Kaplan-Moss, ["REST worst practices"][cite]
+
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
REST framework provides a number of authentication policies out of the box, and also allows you to implement custom policies.
@@ -60,7 +64,7 @@ Or, if you're using the `@api_view` decorator with function based views.
This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. User basic authentication is generally only appropriate for testing.
-**Note:** If you run `UserBasicAuthentication` in production your API must be `https` only, or it will be completely insecure. 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.
+**Note:** If you run `UserBasicAuthentication` in production your API should be `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.
If successfully authenticated, `UserBasicAuthentication` provides the following credentials.
@@ -69,11 +73,13 @@ If successfully authenticated, `UserBasicAuthentication` provides the following
## TokenAuthentication
-This policy uses [HTTP Authentication][basicauth] with no authentication scheme. Token basic authentication is appropriate for client-server setups, such as native desktop and mobile clients. The token key should be passed in as a string to the "Authorization" HTTP header. For example:
+This policy uses simple token-based HTTP Authentication. Token basic authentication is appropriate for client-server setups, such as native desktop and mobile clients.
+
+The token key should be passed in as a string to the "Authorization" HTTP header. For example:
curl http://my.api.org/ -X POST -H "Authorization: 0123456789abcdef0123456789abcdef"
-**Note:** If you run `TokenAuthentication` in production your API must be `https` only, or it will be completely insecure.
+**Note:** If you run `TokenAuthentication` in production your API should be `https` only.
If successfully authenticated, `TokenAuthentication` provides the following credentials.
@@ -102,8 +108,9 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
## Custom authentication policies
-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.
+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.
+[cite]: http://jacobian.org/writing/rest-worst-practices/
[basicauth]: http://tools.ietf.org/html/rfc2617
[oauth]: http://oauth.net/2/
[permission]: permissions.md
diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md
new file mode 100644
index 00000000..01895a4b
--- /dev/null
+++ b/docs/api-guide/content-negotiation.md
@@ -0,0 +1,7 @@
+# Content negotiation
+
+> HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.
+>
+> — [RFC 2616][cite], Fielding et al.
+
+[cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
diff --git a/docs/api-guide/contentnegotiation.md b/docs/api-guide/contentnegotiation.md
deleted file mode 100644
index f01627d8..00000000
--- a/docs/api-guide/contentnegotiation.md
+++ /dev/null
@@ -1 +0,0 @@
-> HTTP has provisions for several mechanisms for "content negotiation" -- the process of selecting the best representation for a given response when there are multiple representations available. -- RFC 2616, Fielding et al.
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
index bb3ed56e..c8ccb08b 100644
--- a/docs/api-guide/exceptions.md
+++ b/docs/api-guide/exceptions.md
@@ -2,4 +2,83 @@
# Exceptions
+> Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
+>
+> — Doug Hellmann, [Python Exception Handling Techniques][cite]
+## Exception handling in REST framework views
+
+REST framework's views handle various exceptions, and deal with returning appropriate error responses for you.
+
+The handled exceptions are:
+
+* Subclasses of `APIException` raised inside REST framework.
+* Django's `Http404` exception.
+* Django's `PermissionDenied` exception.
+
+In each case, REST framework will return a response, rendering it to an appropriate content-type.
+
+By default all error messages will include a key `details` in the body of the response, but other keys may also be included.
+
+For example, the following request:
+
+ DELETE http://api.example.com/foo/bar HTTP/1.1
+ Accept: application/json
+
+Might recieve an error response indicating that the `DELETE` method is not allowed on that resource:
+
+ HTTP/1.1 405 Method Not Allowed
+ Content-Type: application/json; charset=utf-8
+ Content-Length: 42
+
+ {"detail": "Method 'DELETE' not allowed."}
+
+## APIException
+
+**Signature:** `APIException(detail=None)`
+
+The base class for all exceptions raised inside REST framework.
+
+To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class.
+
+## ParseError
+
+**Signature:** `ParseError(detail=None)`
+
+Raised if the request contains malformed data when accessing `request.DATA` or `request.FILES`.
+
+By default this exception results in a response with the HTTP status code "400 Bad Request".
+
+## PermissionDenied
+
+**Signature:** `PermissionDenied(detail=None)`
+
+Raised when an incoming request fails the permission checks.
+
+By default this exception results in a response with the HTTP status code "403 Forbidden".
+
+## MethodNotAllowed
+
+**Signature:** `MethodNotAllowed(method, detail=None)`
+
+Raised when an incoming request occurs that does not map to a handler method on the view.
+
+By default this exception results in a response with the HTTP status code "405 Method Not Allowed".
+
+## UnsupportedMediaType
+
+**Signature:** `UnsupportedMediaType(media_type, detail=None)`
+
+Raised if there are no parsers that can handle the content type of the request data when accessing `request.DATA` or `request.FILES`.
+
+By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
+
+## Throttled
+
+**Signature:** `Throttled(wait=None, detail=None)`
+
+Raised when an incoming request fails the throttling checks.
+
+By default this exception results in a response with the HTTP status code "429 Too Many Requests".
+
+[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
\ No newline at end of file
diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md
new file mode 100644
index 00000000..7d72d9f8
--- /dev/null
+++ b/docs/api-guide/format-suffixes.md
@@ -0,0 +1,11 @@
+
+
+# Format suffixes
+
+> Section 6.2.1 does not say that content negotiation should be
+used all the time.
+>
+> — Roy Fielding, [REST discuss mailing list][cite]
+
+[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857
+
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
new file mode 100644
index 00000000..202875a4
--- /dev/null
+++ b/docs/api-guide/generic-views.md
@@ -0,0 +1,10 @@
+
+
+
+# Generic views
+
+> Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.
+>
+> — [Django Documentation][cite]
+
+[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index 2e15107c..be22eefe 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -1,3 +1,87 @@
-# Permissions
\ No newline at end of file
+# Permissions
+
+> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
+>
+> — [Apple Developer Documentation][cite]
+
+Together with [authentication] and [throttling], permissions determine wheter a request should be granted or denied access.
+
+Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted.
+
+## How permissions are determined
+
+Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view, each permission in the list is checked.
+
+If any permission check fails an `exceptions.PermissionDenied` exception will be raised, and the main body of the view will not run.
+
+## Object level permissions
+
+REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
+
+Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
+
+## Setting the permission policy
+
+The default permission policy may be set globally, using the `DEFAULT_PERMISSIONS` setting. For example.
+
+ API_SETTINGS = {
+ 'DEFAULT_PERMISSIONS': (
+ 'djangorestframework.permissions.IsAuthenticated',
+ )
+ }
+
+You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
+
+ class ExampleView(APIView):
+ permission_classes = (IsAuthenticated,)
+
+ def get(self, request, format=None):
+ content = {
+ 'status': 'request was permitted'
+ }
+ return Response(content)
+
+Or, if you're using the `@api_view` decorator with function based views.
+
+ @api_view('GET')
+ @permission_classes(IsAuthenticated)
+ def example_view(request, format=None):
+ content = {
+ 'status': 'request was permitted'
+ }
+ return Response(content)
+
+## IsAuthenticated
+
+The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise.
+
+This permission is suitable if you want your API to only be accessible to registered users.
+
+## IsAdminUser
+
+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.
+
+## IsAuthenticatedOrReadOnly
+
+The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
+
+This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
+
+## DjangoModelPermissions
+
+This permission class ties into Django's standard `django.contrib.auth` model permissions. When applied to a view that has a `.model` property, permission will only be granted if the user
+
+## Custom permissions
+
+To implement a custom permission, override `BasePermission` and implement the `.check_permission(self, request, obj=None)` method.
+
+The method should return `True` if the request should be granted access, and `False` otherwise.
+
+
+[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
+[authentication]: authentication.md
+[throttling]: throttling.md
\ No newline at end of file
diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md
index 6e42b68e..f3cb0c64 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -1,12 +1,12 @@
-# Returning URIs from your Web APIs
+# Returning URLs
> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
>
> — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite]
-As a rule, it's probably better practice to return absolute URIs from you web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`.
+As a rule, it's probably better practice to return absolute URIs from you Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`.
The advantages of doing so are:
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index ae8dce76..2513928c 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -2,9 +2,13 @@
# Settings
-Configuration for REST framework is all namespaced inside the `API_SETTINGS` setting.
+> Namespaces are one honking great idea - let's do more of those!
+>
+> — [The Zen of Python][cite]
-For example your project's `settings.py` file might look like this:
+Configuration for REST framework is all namespaced inside a single Django setting, named `API_SETTINGS`.
+
+For example your project's `settings.py` file might include something like this:
API_SETTINGS = {
'DEFAULT_RENDERERS': (
@@ -133,3 +137,5 @@ The name of a URL parameter that may be used to override the HTTP `Accept` heade
If the value of this setting is `None` then URL accept overloading will be disabled.
Default: `'_accept'`
+
+[cite]: http://www.python.org/dev/peps/pep-0020/
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index e3a66c83..ae8f7b98 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -1,3 +1,15 @@
# Throttling
+
+> HTTP/1.1 420 Enhance Your Calm
+>
+> [Twitter API rate limiting response][cite]
+
+[cite]: https://dev.twitter.com/docs/error-codes-responses
+
+## PerUserThrottle
+
+## PerViewThrottle
+
+## Custom throttles
\ No newline at end of file
diff --git a/docs/index.md b/docs/index.md
index 46c5cf19..78f4674f 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -77,15 +77,18 @@ The API guide is your complete reference manual to all the functionality provide
* [Requests][request]
* [Responses][response]
* [Views][views]
+* [Generic views][generic-views]
* [Parsers][parsers]
* [Renderers][renderers]
* [Serializers][serializers]
* [Authentication][authentication]
* [Permissions][permissions]
* [Throttling][throttling]
+* [Content negotiation][contentnegotiation]
+* [Format suffixes][formatsuffixes]
+* [Returning URLs][reverse]
* [Exceptions][exceptions]
* [Status codes][status]
-* [Returning URLs][reverse]
* [Settings][settings]
## Topics
@@ -149,15 +152,18 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[request]: api-guide/requests.md
[response]: api-guide/responses.md
[views]: api-guide/views.md
+[generic-views]: api-guide/generic-views.md
[parsers]: api-guide/parsers.md
[renderers]: api-guide/renderers.md
[serializers]: api-guide/serializers.md
[authentication]: api-guide/authentication.md
[permissions]: api-guide/permissions.md
[throttling]: api-guide/throttling.md
+[contentnegotiation]: api-guide/content-negotiation.md
+[formatsuffixes]: api-guide/format-suffixes.md
+[reverse]: api-guide/reverse.md
[exceptions]: api-guide/exceptions.md
[status]: api-guide/status-codes.md
-[reverse]: api-guide/reverse.md
[settings]: api-guide/settings.md
[csrf]: topics/csrf.md
diff --git a/docs/static/css/drf-styles.css b/docs/static/css/drf-styles.css
index bb31b07c..a5f0b97a 100644
--- a/docs/static/css/drf-styles.css
+++ b/docs/static/css/drf-styles.css
@@ -14,15 +14,6 @@ pre {
font-size: 12px;
}
-a.github {
- float: right;
- margin-top: -12px;
-}
-
-a.github:hover {
- text-decoration: none;
-}
-
.dropdown .dropdown-menu {
display: none;
}
@@ -31,25 +22,38 @@ a.github:hover {
display: block;
}
+/* GitHub 'Star' badge */
body.index #main-content iframe {
float: right;
-}
-
-body.index #main-content iframe {
- float: right;
+ margin-top: -12px;
margin-right: -15px;
}
+/* Travis CI badge */
body.index #main-content p:first-of-type {
float: right;
margin-right: 8px;
- margin-top: -1px;
+ margin-top: -14px;
+ margin-bottom: 0px;
}
+/* Github source file badges */
+a.github {
+ float: right;
+ margin-top: -12px;
+ margin-right: 12px;
+}
+
+a.github:hover {
+ text-decoration: none;
+}
+
+/* Force TOC text to not overrun */
#table-of-contents {
overflow: hidden;
}
+/* Code blocks should scroll horizontally */
pre {
overflow: auto;
word-wrap: normal;
@@ -71,13 +75,10 @@ pre {
}
}
-
.nav-list li.main {
font-weight: bold;
}
-
-
/* Set the table of contents to static so it flows back into the content when
viewed on tablets and smaller. */
@media (max-width: 767px) {
@@ -94,7 +95,7 @@ pre {
}
}
-
+/* Cutesy quote styling */
blockquote {
font-family: Georgia, serif;
font-size: 18px;
diff --git a/docs/template.html b/docs/template.html
index c8cfbbab..f20aabac 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -47,15 +47,18 @@
@@ -112,5 +115,9 @@
var shiftWindow = function() { scrollBy(0, -50) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
+
+ $('.dropdown-menu').click(function(event) {
+ event.stopPropagation();
+ });
\ No newline at end of file
--
cgit v1.2.3
From dac4cb9e8bf107f407ed8754bbef0ce97e79beb2 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 12 Sep 2012 13:11:26 +0100
Subject: GitHub link in toolbar
---
docs/api-guide/exceptions.md | 6 +++---
docs/api-guide/permissions.md | 19 ++++++++++++++++---
docs/static/css/drf-styles.css | 7 +++++++
docs/template.html | 1 +
4 files changed, 27 insertions(+), 6 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
index c8ccb08b..c22d6d8b 100644
--- a/docs/api-guide/exceptions.md
+++ b/docs/api-guide/exceptions.md
@@ -8,7 +8,7 @@
## Exception handling in REST framework views
-REST framework's views handle various exceptions, and deal with returning appropriate error responses for you.
+REST framework's views handle various exceptions, and deal with returning appropriate error responses.
The handled exceptions are:
@@ -16,9 +16,9 @@ The handled exceptions are:
* Django's `Http404` exception.
* Django's `PermissionDenied` exception.
-In each case, REST framework will return a response, rendering it to an appropriate content-type.
+In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
-By default all error messages will include a key `details` in the body of the response, but other keys may also be included.
+By default all error responses will include a key `details` in the body of the response, but other keys may also be included.
For example, the following request:
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index be22eefe..e0f3583f 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -12,7 +12,7 @@ Permission checks are always run at the very start of the view, before any other
## How permissions are determined
-Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view, each permission in the list is checked.
+Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view each permission in the list is checked.
If any permission check fails an `exceptions.PermissionDenied` exception will be raised, and the main body of the view will not run.
@@ -73,7 +73,18 @@ This permission is suitable if you want to your API to allow read permissions to
## DjangoModelPermissions
-This permission class ties into Django's standard `django.contrib.auth` model permissions. When applied to a view that has a `.model` property, permission will only be granted if the user
+This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user has the relevant model permissions assigned.
+
+* `POST` requests require the user to have the `add` permission on the model.
+* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
+* `DELETE` requests require the user to have the `delete` permission on the model.
+
+The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
+
+To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
+
+The `DjangoModelPermissions` class also supports object-level permissions. Third-party authorization backends such as [django-guardian][guardian] should work just fine with `DjangoModelPermissions` without any custom configuration required.
+
## Custom permissions
@@ -84,4 +95,6 @@ The method should return `True` if the request should be granted access, and `Fa
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md
-[throttling]: throttling.md
\ No newline at end of file
+[throttling]: throttling.md
+[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions
+[guardian]: https://github.com/lukaszb/django-guardian
\ No newline at end of file
diff --git a/docs/static/css/drf-styles.css b/docs/static/css/drf-styles.css
index a5f0b97a..7ad9d717 100644
--- a/docs/static/css/drf-styles.css
+++ b/docs/static/css/drf-styles.css
@@ -22,6 +22,13 @@ pre {
display: block;
}
+/* Header link to GitHub */
+.repo-link {
+ float: right;
+ margin-right: 10px;
+ margin-top: 7px;
+}
+
/* GitHub 'Star' badge */
body.index #main-content iframe {
float: right;
diff --git a/docs/template.html b/docs/template.html
index f20aabac..936b6d93 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -21,6 +21,7 @@
@@ -122,4 +123,4 @@
event.stopPropagation();
});
-
\ No newline at end of file
+
--
cgit v1.2.3
From dae6d093988ef2830e715d17ad6a0b9f715bfeba Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 1 Oct 2012 16:27:22 +0100
Subject: Add example of using paginator in a view
---
docs/api-guide/pagination.md | 29 +++++++++++++++++++++--------
1 file changed, 21 insertions(+), 8 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 6211a0ac..8ef7c4cc 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -56,19 +56,32 @@ We can do this using the `object_serializer_class` attribute on the inner `Meta`
class Meta:
object_serializer_class = UserSerializer
- queryset = User.objects.all()
- paginator = Paginator(queryset, 20)
- page = paginator.page(1)
- serializer = PaginatedUserSerializer(instance=page)
- serializer.data
- # {'count': 1, 'next': None, 'previous': None, 'results': [{'username': u'admin', 'email': u'admin@example.com'}]}
+We could now use our pagination serializer in a view like this.
+
+ @api_view('GET')
+ def user_list(request):
+ queryset = User.objects.all()
+ paginator = Paginator(queryset, 20)
+
+ page = request.QUERY_PARAMS.get('page')
+ try:
+ users = paginator.page(page)
+ except PageNotAnInteger:
+ # 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.
+ users = paginator.page(paginator.num_pages)
+
+ serializer_context = {'request': request}
+ serializer = PaginatedUserSerializer(instance=users,
+ context=serializer_context)
+ return Response(serializer.data)
## 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.
-## Setting the default pagination style
-
The default pagination style may be set globally, using the `PAGINATION_SERIALIZER` and `PAGINATE_BY` settings. For example.
REST_FRAMEWORK = {
--
cgit v1.2.3
From a8f6ac3f3abdcab298f73f591188012a703a65e2 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 10:39:28 +0100
Subject: Renderer documentation
---
docs/api-guide/renderers.md | 132 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 130 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index d644599e..134c3749 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -6,18 +6,146 @@
>
> — [Django documentation][cite]
+REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexiblity to design your own media types.
+
+## How the renderer is determined
+
+The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.
+
+The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data.
+
+For more information see the documentation on [content negotation][conneg].
+
+## Setting the renderers
+
+The default set of renderers may be set globally, using the `DEFAULT_RENDERERS` setting. For example, the following settings would use `YAML` as the main media type and also include the self describing API.
+
+ REST_FRAMEWORK = {
+ 'DEFAULT_RENDERERS': (
+ 'rest_framework.renderers.YAMLRenderer',
+ 'rest_framework.renderers.DocumentingHTMLRenderer',
+ )
+ }
+
+You can also set the renderers used for an individual view, using the `APIView` class based views.
+
+ class UserCountView(APIView):
+ """
+ A view that returns the count of active users, in JSON or JSONp.
+ """
+ renderer_classes = (JSONRenderer, JSONPRenderer)
+
+ def get(self, request, format=None):
+ user_count = User.objects.filter(active=True).count()
+ content = {'user_count': user_count}
+ return Response(content)
+
+Or, if you're using the `@api_view` decorator with function based views.
+
+ @api_view('GET'),
+ @renderer_classes(JSONRenderer, JSONPRenderer)
+ def user_count_view(request, format=None):
+ """
+ A view that returns the count of active users, in JSON or JSONp.
+ """
+ user_count = User.objects.filter(active=True).count()
+ content = {'user_count': user_count}
+ return Response(content)
+
+## Ordering of renderer classes
+
+It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response.
+
+For example if your API serves JSON responses and the HTML browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
+
+If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers].
+
## JSONRenderer
+**.media_type:** `application/json`
+
+**.format:** `'.json'`
+
## JSONPRenderer
+**.media_type:** `application/javascript`
+
+**.format:** `'.jsonp'`
+
## YAMLRenderer
+**.media_type:** `application/yaml`
+
+**.format:** `'.yaml'`
+
## XMLRenderer
+**.media_type:** `application/xml`
+
+**.format:** `'.xml'`
+
## DocumentingHTMLRenderer
-## TemplatedHTMLRenderer
+**.media_type:** `text/html`
+
+**.format:** `'.api'`
+
+## TemplateHTMLRenderer
+
+**.media_type:** `text/html`
+
+**.format:** `'.html'`
## Custom renderers
-[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
\ No newline at end of file
+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.
+
+## Advanced renderer usage
+
+You can do some pretty flexible things using REST framework's renderers. Some examples...
+
+* Provide either flat or nested representations from the same endpoint, depending on the requested media type.
+* Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
+* Specify multiple types of HTML representation for API clients to use.
+* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
+
+In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
+
+For example:
+
+ @api_view(('GET',))
+ @renderer_classes((TemplateHTMLRenderer, JSONRenderer))
+ @template_name('list_users.html')
+ def list_users(request):
+ """
+ A view that can return JSON or HTML representations
+ of the users in the system.
+ """
+ queryset = Users.objects.filter(active=True)
+
+ if request.accepted_renderer.format == 'html':
+ # TemplateHTMLRenderer takes a context dict,
+ # and does not require serialization.
+ data = {'users': queryset}
+ else:
+ # JSONRenderer requires serialized data as normal.
+ serializer = UserSerializer(instance=queryset)
+ data = serializer.data
+
+ return Response(data)
+
+## Designing your media types
+
+For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll neeed to consider the design and usage of your media types in more detail.
+
+In [the words of Roy Fielding][quote], "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".
+
+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.
+
+[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
+[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
+[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/
\ No newline at end of file
--
cgit v1.2.3
From 2284e592de6315264098e77f72b816984a50d025 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 10:40:04 +0100
Subject: Clean up reverse docs slightly
---
docs/api-guide/reverse.md | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md
index 3fa654c0..07094e6f 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -19,7 +19,9 @@ REST framework provides two utility functions to make it more simple to return a
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
-## reverse(viewname, request, *args, **kwargs)
+## reverse
+
+**Signature:** `reverse(viewname, request, *args, **kwargs)`
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
@@ -34,7 +36,9 @@ Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except t
}
return Response(content)
-## reverse_lazy(viewname, request, *args, **kwargs)
+## reverse_lazy
+
+**Signature:** `reverse_lazy(viewname, request, *args, **kwargs)`
Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
--
cgit v1.2.3
From ae8a8270042820f92b9d43597bde50d72c300513 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 10:40:43 +0100
Subject: Make 'results_field' attribute of BasePaginationSerializer public.
---
docs/api-guide/pagination.md | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index 8ef7c4cc..50be59bf 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -104,7 +104,9 @@ For more complex requirements such as serialization that differs depending on th
To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return.
-For example, to nest a pair of links labelled 'prev' and 'next' you might use something like this.
+You can also override the name used for the object list field, by setting the `results_field` attribute, which defaults to `'results'`.
+
+For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
class LinksSerializer(serializers.Serializer):
next = pagination.NextURLField(source='*')
@@ -114,4 +116,6 @@ For example, to nest a pair of links labelled 'prev' and 'next' you might use so
links = LinksSerializer(source='*') # Takes the page object as the source
total_results = serializers.Field(source='paginator.count')
+ results_field = 'objects'
+
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
--
cgit v1.2.3
From 34637bf8578bdfff2d60f36e6e5ac6314a330eaf Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 11:03:51 +0100
Subject: Make example more realistic and less of a toy
---
docs/api-guide/reverse.md | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md
index 07094e6f..8485087e 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -25,16 +25,18 @@ There's no requirement for you to use them, but if you do then the self-describi
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
+ import datetime
from rest_framework.utils import reverse
from rest_framework.views import APIView
- class MyView(APIView):
+ class APIRootView(APIView):
def get(self, request):
- content = {
+ year = datetime.datetime.now().year
+ data = {
...
- 'url': reverse('year-summary', request, args=[1945])
+ 'year-summary-url': reverse('year-summary', request, args=[year])
}
- return Response(content)
+ return Response(data)
## reverse_lazy
--
cgit v1.2.3
From b526b82abf4be55faa7610bdeeefa340f84ad2d1 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 11:04:06 +0100
Subject: Placeholder for FBV docs
---
docs/api-guide/views.md | 15 +++++++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index e7f12b45..37d2285b 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -1,6 +1,6 @@
-# Views
+# Class Based Views
> Django's class based views are a welcome departure from the old-style views.
>
@@ -110,4 +110,15 @@ Ensures that any `Response` object returned from the handler method will be rend
You won't typically need to override this method.
-[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
\ No newline at end of file
+# Function Based Views
+
+> Saying [that Class based views] is always the superior solution is a mistake.
+>
+> — [Nick Coghlan][cite2]
+
+REST framework also gives you to work with regular function based views...
+
+**[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
\ No newline at end of file
--
cgit v1.2.3
From 8855a462c606c4cb08a86269c1f46dc2b30fc1ac Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 11:48:25 +0100
Subject: Clean up docs slightly
---
docs/api-guide/generic-views.md | 88 +++++++++++++++++++++++++++++++++++++++++
docs/api-guide/views.md | 2 +
2 files changed, 90 insertions(+)
(limited to 'docs')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 202875a4..88f245c7 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -7,4 +7,92 @@
>
> — [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.
+
+## Example
+
+...
+
+---
+
+# API Reference
+
+## ListAPIView
+
+Used for read-write endpoints to represent a collection of model instances.
+
+Provides a `get` method handler.
+
+## ListCreateAPIView
+
+Used for read-write endpoints to represent a collection of model instances.
+
+Provides `get` and `post` method handlers.
+
+## RetrieveAPIView
+
+Used for read-only endpoints to represent a single model instance.
+
+Provides a `get` method handler.
+
+## RetrieveUpdateDestroyAPIView
+
+Used for read-write endpoints to represent a single model instance.
+
+Provides `get`, `put` and `delete` method handlers.
+
+---
+
+# Base views
+
+## BaseAPIView
+
+Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
+
+## MultipleObjectBaseAPIView
+
+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].
+
+## SingleObjectBaseAPIView
+
+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].
+
+---
+
+# Mixins
+
+The mixin classes provide the actions that are used
+
+## ListModelMixin
+
+Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
+
+## CreateModelMixin
+
+Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
+
+## RetrieveModelMixin
+
+Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
+
+## UpdateModelMixin
+
+Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
+
+## DestroyModelMixin
+
+Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
+
+## MetadataMixin
+
+Provides a `.metadata(request, *args, **kwargs)` method, that returns a response containing metadata about the view.
+
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
+[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/
+[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/
+[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/
+[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 37d2285b..a615026f 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -110,6 +110,8 @@ Ensures that any `Response` object returned from the handler method will be rend
You won't typically need to override this method.
+---
+
# Function Based Views
> Saying [that Class based views] is always the superior solution is a mistake.
--
cgit v1.2.3
From e7685f3eb5c7d7e8fb1678d673f03688012b00cb Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 15:24:42 +0100
Subject: URL overrides in settings fixed up slightly
---
docs/api-guide/settings.md | 6 +++++-
docs/topics/formoverloading.md | 12 ++++++------
2 files changed, 11 insertions(+), 7 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 0f66e85e..43be0d47 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -136,6 +136,10 @@ The name of a URL parameter that may be used to override the HTTP `Accept` heade
If the value of this setting is `None` then URL accept overloading will be disabled.
-Default: `'_accept'`
+Default: `'accept'`
+
+## URL_FORMAT_OVERRIDE
+
+Default: `'format'`
[cite]: http://www.python.org/dev/peps/pep-0020/
diff --git a/docs/topics/formoverloading.md b/docs/topics/formoverloading.md
index a1828c3b..96cb1388 100644
--- a/docs/topics/formoverloading.md
+++ b/docs/topics/formoverloading.md
@@ -1,10 +1,10 @@
-# Browser based PUT & DELETE
+# Browser hacks
> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"
>
> — [RESTful Web Services](1), Leonard Richardson & Sam Ruby.
-## Overloading the HTTP method
+## Browser based PUT, DELETE, etc...
**TODO: Preamble.** Note that this is the same strategy as is used in [Ruby on Rails](2).
@@ -16,7 +16,7 @@ For example, given the following form:
`request.method` would return `"DELETE"`.
-## Overloading the HTTP content type
+## Browser based submission of non-form content
Browser-based submission of content types other than form are supported by using form fields named `_content` and `_content_type`:
@@ -29,13 +29,13 @@ For example, given the following form:
`request.content_type` would return `"application/json"`, and `request.content` would return `"{'count': 1}"`
-## Why not just use Javascript?
+## URL based accept headers
-**[TODO]**
+## URL based format suffixes
## Doesn't HTML5 support PUT and DELETE forms?
-Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec](3). There remains [ongoing discussion](4) about adding support for `PUT` and `DELETE`, as well as how to support content-types other than form-encoded data.
+Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec](3). There remains [ongoing discussion](4) about adding support for `PUT` and `DELETE`, as well as how to support content types other than form-encoded data.
[1]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
[2]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
--
cgit v1.2.3
From ab173fd8f9070ccdb70f86f400d2ffa780977ce4 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 15:37:13 +0100
Subject: Fix bug where pk could be set in post data
---
docs/api-guide/serializers.md | 3 +++
1 file changed, 3 insertions(+)
(limited to 'docs')
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index 38a1e560..4ddc6e0a 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -230,6 +230,9 @@ The `nested` option may also be set by passing it to the `serialize()` method.
class Meta:
model = Account
+ def get_pk_field(self, model_field):
+ return Field(readonly=True)
+
def get_nested_field(self, model_field):
return ModelSerializer()
--
cgit v1.2.3
From 31b06f1721f98730556dc56927b985e4032788c3 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 19:54:20 +0100
Subject: Cleaner travis image link
---
docs/index.md | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index e7db5dbc..6e4d6257 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,5 +1,5 @@
-[][travis]
+[![travis-build-image]][travis]
# Django REST framework
@@ -140,6 +140,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=restframework2
+[travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2
[urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML
--
cgit v1.2.3
From b89125ef53a2f9e246afd5eda5c8f404a714da76 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 2 Oct 2012 21:26:15 +0100
Subject: Update view docs slightly
---
docs/api-guide/generic-views.md | 43 +++++++++++++++++++++++++++++++++--------
1 file changed, 35 insertions(+), 8 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 88f245c7..b2284ae5 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -9,9 +9,38 @@
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.
-## Example
+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.
+
+## Examples
+
+Typically when using the generic views, you'll override the view, and set several class attributes.
+
+ class UserList(generics.ListCreateAPIView):
+ serializer = UserSerializer
+ model = User
+ permissions = (IsAdminUser,)
+ paginate_by = 100
+
+For more complex cases you might also want to override various methods on the view class. For example.
+
+ class UserList(generics.ListCreateAPIView):
+ serializer = UserSerializer
+ model = User
+ permissions = (IsAdminUser,)
+
+ def get_paginate_by(self):
+ """
+ Use smaller pagination for HTML representations.
+ """
+ if self.request.accepted_media_type == 'text/html':
+ return 10
+ return 100
+
+For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
+
+ url(r'^/users/', ListCreateAPIView.as_view(model=User) name='user-list')
---
@@ -19,7 +48,7 @@ One of the key benefits of class based views is the way they allow you to compos
## ListAPIView
-Used for read-write endpoints to represent a collection of model instances.
+Used for read-only endpoints to represent a collection of model instances.
Provides a `get` method handler.
@@ -45,6 +74,8 @@ Provides `get`, `put` and `delete` method handlers.
# Base views
+Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes.
+
## BaseAPIView
Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
@@ -65,7 +96,7 @@ Provides a base view for acting on a single object, by combining REST framework'
# Mixins
-The mixin classes provide the actions that are used
+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
@@ -87,10 +118,6 @@ Provides a `.update(request, *args, **kwargs)` method, that implements updating
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
-## MetadataMixin
-
-Provides a `.metadata(request, *args, **kwargs)` method, that returns a response containing metadata about the view.
-
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/
[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/
--
cgit v1.2.3
From 934492ebd02dfc580fd0dbd9d8a57ca123adb46d Mon Sep 17 00:00:00 2001
From: Matt Bosworth
Date: Tue, 2 Oct 2012 22:41:03 -0700
Subject: Fixed references to serializer.serialized and
serializer.serialized_errors in part 3 of the tutorial. Altered part 1 to
use blogs/urls.py since it was specified at the beginning. Also caught some
spelling errors while I was at it.
---
docs/tutorial/1-serialization.md | 6 +++---
docs/tutorial/2-requests-and-responses.md | 4 ++--
docs/tutorial/3-class-based-views.md | 8 ++++----
docs/tutorial/6-resource-orientated-projects.md | 6 +++---
4 files changed, 12 insertions(+), 12 deletions(-)
(limited to 'docs')
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index cd4b7558..5d830315 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -78,7 +78,7 @@ Don't forget to sync the database for the first time.
## Creating a Serializer class
-We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as `json`. We do this by declaring serializers, that work very similarly to Django's forms. Create a file in the project named `serializers.py` and add the following.
+We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as `json`. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the project named `serializers.py` and add the following.
from blog import models
from rest_framework import serializers
@@ -201,7 +201,7 @@ The root of our API is going to be a view that supports listing all the existing
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
-We'll also need a view which corrosponds to an individual comment, and can be used to retrieve, update or delete the comment.
+We'll also need a view which corresponds to an individual comment, and can be used to retrieve, update or delete the comment.
@csrf_exempt
def comment_instance(request, pk):
@@ -231,7 +231,7 @@ We'll also need a view which corrosponds to an individual comment, and can be us
comment.delete()
return HttpResponse(status=204)
-Finally we need to wire these views up, in the `tutorial/urls.py` file.
+Finally we need to wire these views up. Create the `blog/urls.py` file:
from django.conf.urls import patterns, url
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index d889b1e0..13feb254 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -27,7 +27,7 @@ REST framework provides two wrappers you can use to write API views.
1. The `@api_view` decorator for working with function based views.
2. The `APIView` class for working with class based views.
-These wrappers provide a few bits of functionality such as making sure you recieve `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
+These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
@@ -121,7 +121,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
urlpatterns = format_suffix_patterns(urlpatterns)
-We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of refering to a specific format.
+We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format.
## How's it looking?
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index 25d5773f..b2b6443c 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -28,10 +28,10 @@ We'll start by rewriting the root view as a class based view. All this involves
if serializer.is_valid():
comment = serializer.object
comment.save()
- return Response(serializer.serialized, status=status.HTTP_201_CREATED)
- return Response(serializer.serialized_errors, status=status.HTTP_400_BAD_REQUEST)
+ return Response(serializer.data, status=status.HTTP_201_CREATED)
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
-So far, so good. It looks pretty similar to the previous case, but we've got better seperation between the different HTTP methods. We'll also need to update the instance view.
+So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view.
class CommentInstance(APIView):
"""
@@ -145,7 +145,7 @@ Using the mixin classes we've rewritten the views to use slightly less code than
model = Comment
serializer_class = CommentSerializer
-Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idomatic Django.
+Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic Django.
Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
diff --git a/docs/tutorial/6-resource-orientated-projects.md b/docs/tutorial/6-resource-orientated-projects.md
index 3c3e7fed..e7190a77 100644
--- a/docs/tutorial/6-resource-orientated-projects.md
+++ b/docs/tutorial/6-resource-orientated-projects.md
@@ -4,8 +4,8 @@ Resource classes are just View classes that don't have any handler methods bound
This allows us to:
-* Encapsulate common behaviour accross a class of views, in a single Resource class.
-* Seperate out the actions of a Resource from the specfics of how those actions should be bound to a particular set of URLs.
+* Encapsulate common behaviour across a class of views, in a single Resource class.
+* Separate out the actions of a Resource from the specfics of how those actions should be bound to a particular set of URLs.
## Refactoring to use Resources, not Views
@@ -59,7 +59,7 @@ Right now that hasn't really saved us a lot of code. However, now that we're us
## Trade-offs between views vs resources.
-Writing resource-orientated code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write.
+Writing resource-oriented code can be a good thing. It helps ensure that URL conventions will be consistent across your APIs, and minimises the amount of code you need to write.
The trade-off is that the behaviour is less explict. It can be more difficult to determine what code path is being followed, or where to override some behaviour.
--
cgit v1.2.3
From c30e0795bebd9980a66ae7db1a0d8c43f77d4c11 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Wed, 3 Oct 2012 09:26:15 +0100
Subject: Rename generic views
---
docs/tutorial/3-class-based-views.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index 25d5773f..663138bd 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -136,12 +136,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than
from rest_framework import generics
- class CommentRoot(generics.RootAPIView):
+ class CommentRoot(generics.ListCreateAPIView):
model = Comment
serializer_class = CommentSerializer
- class CommentInstance(generics.InstanceAPIView):
+ class CommentInstance(generics.RetrieveUpdateDestroyAPIView):
model = Comment
serializer_class = CommentSerializer
--
cgit v1.2.3
From bcd2caf5598a71cb468d86b6f286e180d1bf0a19 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Thu, 4 Oct 2012 09:18:46 +0100
Subject: Abstract out the app_label on test models
---
docs/api-guide/fields.md | 43 +++++++++++++++++++++++++++++++++++++++++++
1 file changed, 43 insertions(+)
create mode 100644 docs/api-guide/fields.md
(limited to 'docs')
diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md
new file mode 100644
index 00000000..009d2a79
--- /dev/null
+++ b/docs/api-guide/fields.md
@@ -0,0 +1,43 @@
+
+
+# Serializer fields
+
+> Flat is better than nested.
+>
+> — [The Zen of Python][cite]
+
+# Generic Fields
+
+## Field
+
+## ModelField
+
+# Typed Fields
+
+## BooleanField
+
+## CharField
+
+## EmailField
+
+## DateField
+
+## DateTimeField
+
+## IntegerField
+
+## FloatField
+
+# Relational Fields
+
+Relational fields are used to represent model relationships.
+
+## PrimaryKeyRelatedField
+
+## ManyPrimaryKeyRelatedField
+
+## HyperlinkedRelatedField
+
+## ManyHyperlinkedRelatedField
+
+[cite]: http://www.python.org/dev/peps/pep-0020/
--
cgit v1.2.3
From d07dc77e91c1f99b47915b3cef30b565f2618e82 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 5 Oct 2012 10:23:47 +0100
Subject: Accepted media type uses most specific of client/renderer media
types.
---
docs/api-guide/generic-views.md | 29 +++++++++++++++++++++++------
docs/api-guide/renderers.md | 14 +++++++-------
docs/index.md | 2 +-
3 files changed, 31 insertions(+), 14 deletions(-)
(limited to 'docs')
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index b2284ae5..571cc66f 100644
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -18,24 +18,25 @@ If the generic views don't suit the needs of your API, you can drop down to usin
Typically when using the generic views, you'll override the view, and set several class attributes.
class UserList(generics.ListCreateAPIView):
- serializer = UserSerializer
model = User
- permissions = (IsAdminUser,)
+ serializer_class = UserSerializer
+ permission_classes = (IsAdminUser,)
paginate_by = 100
For more complex cases you might also want to override various methods on the view class. For example.
class UserList(generics.ListCreateAPIView):
- serializer = UserSerializer
model = User
- permissions = (IsAdminUser,)
+ serializer_class = UserSerializer
+ permission_classes = (IsAdminUser,)
def get_paginate_by(self):
"""
Use smaller pagination for HTML representations.
"""
- if self.request.accepted_media_type == 'text/html':
- return 10
+ page_size_param = self.request.QUERY_PARAMS.get('page_size')
+ if page_size_param:
+ return int(page_size_param)
return 100
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
@@ -52,24 +53,32 @@ Used for read-only endpoints to represent a collection of model instances.
Provides a `get` method handler.
+Extends: [MultipleObjectBaseAPIView], [ListModelMixin]
+
## ListCreateAPIView
Used for read-write endpoints to represent a collection of model instances.
Provides `get` and `post` method handlers.
+Extends: [MultipleObjectBaseAPIView], [ListModelMixin], [CreateModelMixin]
+
## RetrieveAPIView
Used for read-only endpoints to represent a single model instance.
Provides a `get` method handler.
+Extends: [SingleObjectBaseAPIView], [RetrieveModelMixin]
+
## RetrieveUpdateDestroyAPIView
Used for read-write endpoints to represent a single model instance.
Provides `get`, `put` and `delete` method handlers.
+Extends: [SingleObjectBaseAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
+
---
# Base views
@@ -123,3 +132,11 @@ Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion
[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/
[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/
[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/
+
+[SingleObjectBaseAPIView]: #singleobjectbaseapiview
+[MultipleObjectBaseAPIView]: #multipleobjectbaseapiview
+[ListModelMixin]: #listmodelmixin
+[CreateModelMixin]: #createmodelmixin
+[RetrieveModelMixin]: #retrievemodelmixin
+[UpdateModelMixin]: #updatemodelmixin
+[DestroyModelMixin]: #destroymodelmixin
\ No newline at end of file
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 134c3749..e1c83477 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -115,7 +115,6 @@ For example:
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
- @template_name('list_users.html')
def list_users(request):
"""
A view that can return JSON or HTML representations
@@ -123,15 +122,16 @@ For example:
"""
queryset = Users.objects.filter(active=True)
- if request.accepted_renderer.format == 'html':
+ if request.accepted_media_type == 'text/html':
# TemplateHTMLRenderer takes a context dict,
- # and does not require serialization.
+ # and additionally requiresa 'template_name'.
+ # It does not require serialization.
data = {'users': queryset}
- else:
- # JSONRenderer requires serialized data as normal.
- serializer = UserSerializer(instance=queryset)
- data = serializer.data
+ return Response(data, template='list_users.html')
+ # JSONRenderer requires serialized data as normal.
+ serializer = UserSerializer(instance=queryset)
+ data = serializer.data
return Response(data)
## Designing your media types
diff --git a/docs/index.md b/docs/index.md
index e301f77a..0b49c5ec 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -58,7 +58,7 @@ Note that the base URL can be whatever you want, but you must include `rest_fram
## Quickstart
-**TODO**
+
## Tutorial
--
cgit v1.2.3
From 26c7d6df6c0a12a2e19e07951b93de80bbfdf91c Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Fri, 5 Oct 2012 12:13:44 +0100
Subject: HTMLTemplateRenderer working
---
docs/api-guide/renderers.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index e1c83477..ef0ed46f 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -127,7 +127,7 @@ For example:
# and additionally requiresa 'template_name'.
# It does not require serialization.
data = {'users': queryset}
- return Response(data, template='list_users.html')
+ return Response(data, template_name='list_users.html')
# JSONRenderer requires serialized data as normal.
serializer = UserSerializer(instance=queryset)
--
cgit v1.2.3
From f70a5edc1f538d80c507a776ea670b01adee06f0 Mon Sep 17 00:00:00 2001
From: Max Hurl
Date: Fri, 5 Oct 2012 12:29:53 +0100
Subject: Added dabapps styles and general improvements to docs
---
docs/static/css/bootstrap-responsive.css | 2 +-
docs/static/css/bootstrap.css | 2 +-
docs/static/css/default.css | 70 ++++++++
docs/static/img/grid.png | Bin 0 -> 1458 bytes
docs/static/js/bootstrap-affix.js | 104 -----------
docs/static/js/bootstrap-alert.js | 90 ----------
docs/static/js/bootstrap-button.js | 96 ----------
docs/static/js/bootstrap-carousel.js | 176 ------------------
docs/static/js/bootstrap-collapse.js | 158 ----------------
docs/static/js/bootstrap-dropdown.js | 150 ----------------
docs/static/js/bootstrap-modal.js | 239 ------------------------
docs/static/js/bootstrap-popover.js | 103 -----------
docs/static/js/bootstrap-scrollspy.js | 151 ----------------
docs/static/js/bootstrap-tab.js | 135 --------------
docs/static/js/bootstrap-tooltip.js | 275 ----------------------------
docs/static/js/bootstrap-transition.js | 60 -------
docs/static/js/bootstrap-typeahead.js | 300 -------------------------------
docs/static/js/bootstrap.min.js | 7 +
docs/template.html | 10 +-
19 files changed, 84 insertions(+), 2044 deletions(-)
mode change 100644 => 100755 docs/static/css/bootstrap-responsive.css
mode change 100644 => 100755 docs/static/css/bootstrap.css
create mode 100644 docs/static/img/grid.png
delete mode 100755 docs/static/js/bootstrap-affix.js
delete mode 100755 docs/static/js/bootstrap-alert.js
delete mode 100755 docs/static/js/bootstrap-button.js
delete mode 100755 docs/static/js/bootstrap-carousel.js
delete mode 100755 docs/static/js/bootstrap-collapse.js
delete mode 100755 docs/static/js/bootstrap-dropdown.js
delete mode 100755 docs/static/js/bootstrap-modal.js
delete mode 100755 docs/static/js/bootstrap-popover.js
delete mode 100755 docs/static/js/bootstrap-scrollspy.js
delete mode 100755 docs/static/js/bootstrap-tab.js
delete mode 100755 docs/static/js/bootstrap-tooltip.js
delete mode 100755 docs/static/js/bootstrap-transition.js
delete mode 100755 docs/static/js/bootstrap-typeahead.js
create mode 100755 docs/static/js/bootstrap.min.js
(limited to 'docs')
diff --git a/docs/static/css/bootstrap-responsive.css b/docs/static/css/bootstrap-responsive.css
old mode 100644
new mode 100755
index 9259d26d..a8caf451
--- a/docs/static/css/bootstrap-responsive.css
+++ b/docs/static/css/bootstrap-responsive.css
@@ -1055,4 +1055,4 @@
height: auto !important;
overflow: visible !important;
}
-}
+}
\ No newline at end of file
diff --git a/docs/static/css/bootstrap.css b/docs/static/css/bootstrap.css
old mode 100644
new mode 100755
index 9fa6f766..53df6859
--- a/docs/static/css/bootstrap.css
+++ b/docs/static/css/bootstrap.css
@@ -5771,4 +5771,4 @@ a.badge:hover {
.affix {
position: fixed;
-}
+}
\ No newline at end of file
diff --git a/docs/static/css/default.css b/docs/static/css/default.css
index 49aac3a3..28cd9a19 100644
--- a/docs/static/css/default.css
+++ b/docs/static/css/default.css
@@ -64,6 +64,7 @@ a.github:hover {
/* Force TOC text to not overrun */
#table-of-contents {
overflow: hidden;
+ margin: 0 0 20px 0;
}
/* Code blocks should scroll horizontally */
@@ -138,3 +139,72 @@ blockquote p:last-child {
margin-top: 5px;
}
+
+/*=== dabapps bootstrap styles ====*/
+
+html{
+ width:100%;
+ background: none;
+}
+
+body, .navbar .navbar-inner .container-fluid{
+ max-width: 1150px;
+ margin: 0 auto;
+}
+
+body{
+ background: url("../img/grid.png") repeat-x;
+}
+
+/* custom navigation styles */
+
+.navbar .navbar-inner{
+ background: #2C2C2C;
+ color: white;
+ border: none;
+ border-top: 5px solid #A30000;
+}
+
+.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{
+ color: white;
+}
+
+.nav-list > .active > a, .nav-list > .active > a:hover {
+ background: #2c2c2c;
+}
+
+.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{
+ color: #A30000;
+}
+.navbar .navbar-inner .dropdown-menu li a:hover{
+ background: #eeeeee;
+ color: #c20000;
+}
+
+/* custom general page styles */
+.hero-unit h2, .hero-unit h1{
+ color: #A30000;
+}
+
+body a{
+ color: #A30000;
+}
+
+body a:hover{
+ color: #c20000;
+}
+
+/* subnavigation styles */
+
+@media (min-width: 767px) {
+ .sidebar-nav-fixed {
+ position:fixed;
+ width:19%;
+ max-width: 240px;
+ }
+
+ .navbar .navbar-inner .container-fluid{
+ max-width: 1110px;
+ }
+ }
+
diff --git a/docs/static/img/grid.png b/docs/static/img/grid.png
new file mode 100644
index 00000000..878c3ed5
Binary files /dev/null and b/docs/static/img/grid.png differ
diff --git a/docs/static/js/bootstrap-affix.js b/docs/static/js/bootstrap-affix.js
deleted file mode 100755
index c49d6e9d..00000000
--- a/docs/static/js/bootstrap-affix.js
+++ /dev/null
@@ -1,104 +0,0 @@
-/* ==========================================================
- * bootstrap-affix.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#affix
- * ==========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* AFFIX CLASS DEFINITION
- * ====================== */
-
- var Affix = function (element, options) {
- this.options = $.extend({}, $.fn.affix.defaults, options)
- this.$window = $(window).on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
- this.$element = $(element)
- this.checkPosition()
- }
-
- Affix.prototype.checkPosition = function () {
- if (!this.$element.is(':visible')) return
-
- var scrollHeight = $(document).height()
- , scrollTop = this.$window.scrollTop()
- , position = this.$element.offset()
- , offset = this.options.offset
- , offsetBottom = offset.bottom
- , offsetTop = offset.top
- , reset = 'affix affix-top affix-bottom'
- , affix
-
- if (typeof offset != 'object') offsetBottom = offsetTop = offset
- if (typeof offsetTop == 'function') offsetTop = offset.top()
- if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
-
- affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ?
- false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ?
- 'bottom' : offsetTop != null && scrollTop <= offsetTop ?
- 'top' : false
-
- if (this.affixed === affix) return
-
- this.affixed = affix
- this.unpin = affix == 'bottom' ? position.top - scrollTop : null
-
- this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''))
- }
-
-
- /* AFFIX PLUGIN DEFINITION
- * ======================= */
-
- $.fn.affix = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('affix')
- , options = typeof option == 'object' && option
- if (!data) $this.data('affix', (data = new Affix(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.affix.Constructor = Affix
-
- $.fn.affix.defaults = {
- offset: 0
- }
-
-
- /* AFFIX DATA-API
- * ============== */
-
- $(window).on('load', function () {
- $('[data-spy="affix"]').each(function () {
- var $spy = $(this)
- , data = $spy.data()
-
- data.offset = data.offset || {}
-
- data.offsetBottom && (data.offset.bottom = data.offsetBottom)
- data.offsetTop && (data.offset.top = data.offsetTop)
-
- $spy.affix(data)
- })
- })
-
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-alert.js b/docs/static/js/bootstrap-alert.js
deleted file mode 100755
index 51273ab9..00000000
--- a/docs/static/js/bootstrap-alert.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* ==========================================================
- * bootstrap-alert.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#alerts
- * ==========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* ALERT CLASS DEFINITION
- * ====================== */
-
- var dismiss = '[data-dismiss="alert"]'
- , Alert = function (el) {
- $(el).on('click', dismiss, this.close)
- }
-
- Alert.prototype.close = function (e) {
- var $this = $(this)
- , selector = $this.attr('data-target')
- , $parent
-
- if (!selector) {
- selector = $this.attr('href')
- selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
- }
-
- $parent = $(selector)
-
- e && e.preventDefault()
-
- $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())
-
- $parent.trigger(e = $.Event('close'))
-
- if (e.isDefaultPrevented()) return
-
- $parent.removeClass('in')
-
- function removeElement() {
- $parent
- .trigger('closed')
- .remove()
- }
-
- $.support.transition && $parent.hasClass('fade') ?
- $parent.on($.support.transition.end, removeElement) :
- removeElement()
- }
-
-
- /* ALERT PLUGIN DEFINITION
- * ======================= */
-
- $.fn.alert = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('alert')
- if (!data) $this.data('alert', (data = new Alert(this)))
- if (typeof option == 'string') data[option].call($this)
- })
- }
-
- $.fn.alert.Constructor = Alert
-
-
- /* ALERT DATA-API
- * ============== */
-
- $(function () {
- $('body').on('click.alert.data-api', dismiss, Alert.prototype.close)
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-button.js b/docs/static/js/bootstrap-button.js
deleted file mode 100755
index a0ab0bfa..00000000
--- a/docs/static/js/bootstrap-button.js
+++ /dev/null
@@ -1,96 +0,0 @@
-/* ============================================================
- * bootstrap-button.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#buttons
- * ============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* BUTTON PUBLIC CLASS DEFINITION
- * ============================== */
-
- var Button = function (element, options) {
- this.$element = $(element)
- this.options = $.extend({}, $.fn.button.defaults, options)
- }
-
- Button.prototype.setState = function (state) {
- var d = 'disabled'
- , $el = this.$element
- , data = $el.data()
- , val = $el.is('input') ? 'val' : 'html'
-
- state = state + 'Text'
- data.resetText || $el.data('resetText', $el[val]())
-
- $el[val](data[state] || this.options[state])
-
- // push to event loop to allow forms to submit
- setTimeout(function () {
- state == 'loadingText' ?
- $el.addClass(d).attr(d, d) :
- $el.removeClass(d).removeAttr(d)
- }, 0)
- }
-
- Button.prototype.toggle = function () {
- var $parent = this.$element.closest('[data-toggle="buttons-radio"]')
-
- $parent && $parent
- .find('.active')
- .removeClass('active')
-
- this.$element.toggleClass('active')
- }
-
-
- /* BUTTON PLUGIN DEFINITION
- * ======================== */
-
- $.fn.button = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('button')
- , options = typeof option == 'object' && option
- if (!data) $this.data('button', (data = new Button(this, options)))
- if (option == 'toggle') data.toggle()
- else if (option) data.setState(option)
- })
- }
-
- $.fn.button.defaults = {
- loadingText: 'loading...'
- }
-
- $.fn.button.Constructor = Button
-
-
- /* BUTTON DATA-API
- * =============== */
-
- $(function () {
- $('body').on('click.button.data-api', '[data-toggle^=button]', function ( e ) {
- var $btn = $(e.target)
- if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
- $btn.button('toggle')
- })
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-carousel.js b/docs/static/js/bootstrap-carousel.js
deleted file mode 100755
index 5c194b42..00000000
--- a/docs/static/js/bootstrap-carousel.js
+++ /dev/null
@@ -1,176 +0,0 @@
-/* ==========================================================
- * bootstrap-carousel.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#carousel
- * ==========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* CAROUSEL CLASS DEFINITION
- * ========================= */
-
- var Carousel = function (element, options) {
- this.$element = $(element)
- this.options = options
- this.options.slide && this.slide(this.options.slide)
- this.options.pause == 'hover' && this.$element
- .on('mouseenter', $.proxy(this.pause, this))
- .on('mouseleave', $.proxy(this.cycle, this))
- }
-
- Carousel.prototype = {
-
- cycle: function (e) {
- if (!e) this.paused = false
- this.options.interval
- && !this.paused
- && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
- return this
- }
-
- , to: function (pos) {
- var $active = this.$element.find('.item.active')
- , children = $active.parent().children()
- , activePos = children.index($active)
- , that = this
-
- if (pos > (children.length - 1) || pos < 0) return
-
- if (this.sliding) {
- return this.$element.one('slid', function () {
- that.to(pos)
- })
- }
-
- if (activePos == pos) {
- return this.pause().cycle()
- }
-
- return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
- }
-
- , pause: function (e) {
- if (!e) this.paused = true
- if (this.$element.find('.next, .prev').length && $.support.transition.end) {
- this.$element.trigger($.support.transition.end)
- this.cycle()
- }
- clearInterval(this.interval)
- this.interval = null
- return this
- }
-
- , next: function () {
- if (this.sliding) return
- return this.slide('next')
- }
-
- , prev: function () {
- if (this.sliding) return
- return this.slide('prev')
- }
-
- , slide: function (type, next) {
- var $active = this.$element.find('.item.active')
- , $next = next || $active[type]()
- , isCycling = this.interval
- , direction = type == 'next' ? 'left' : 'right'
- , fallback = type == 'next' ? 'first' : 'last'
- , that = this
- , e = $.Event('slide', {
- relatedTarget: $next[0]
- })
-
- this.sliding = true
-
- isCycling && this.pause()
-
- $next = $next.length ? $next : this.$element.find('.item')[fallback]()
-
- if ($next.hasClass('active')) return
-
- if ($.support.transition && this.$element.hasClass('slide')) {
- this.$element.trigger(e)
- if (e.isDefaultPrevented()) return
- $next.addClass(type)
- $next[0].offsetWidth // force reflow
- $active.addClass(direction)
- $next.addClass(direction)
- this.$element.one($.support.transition.end, function () {
- $next.removeClass([type, direction].join(' ')).addClass('active')
- $active.removeClass(['active', direction].join(' '))
- that.sliding = false
- setTimeout(function () { that.$element.trigger('slid') }, 0)
- })
- } else {
- this.$element.trigger(e)
- if (e.isDefaultPrevented()) return
- $active.removeClass('active')
- $next.addClass('active')
- this.sliding = false
- this.$element.trigger('slid')
- }
-
- isCycling && this.cycle()
-
- return this
- }
-
- }
-
-
- /* CAROUSEL PLUGIN DEFINITION
- * ========================== */
-
- $.fn.carousel = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('carousel')
- , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option)
- , action = typeof option == 'string' ? option : options.slide
- if (!data) $this.data('carousel', (data = new Carousel(this, options)))
- if (typeof option == 'number') data.to(option)
- else if (action) data[action]()
- else if (options.interval) data.cycle()
- })
- }
-
- $.fn.carousel.defaults = {
- interval: 5000
- , pause: 'hover'
- }
-
- $.fn.carousel.Constructor = Carousel
-
-
- /* CAROUSEL DATA-API
- * ================= */
-
- $(function () {
- $('body').on('click.carousel.data-api', '[data-slide]', function ( e ) {
- var $this = $(this), href
- , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
- , options = !$target.data('modal') && $.extend({}, $target.data(), $this.data())
- $target.carousel(options)
- e.preventDefault()
- })
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-collapse.js b/docs/static/js/bootstrap-collapse.js
deleted file mode 100755
index 8116f225..00000000
--- a/docs/static/js/bootstrap-collapse.js
+++ /dev/null
@@ -1,158 +0,0 @@
-/* =============================================================
- * bootstrap-collapse.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#collapse
- * =============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* COLLAPSE PUBLIC CLASS DEFINITION
- * ================================ */
-
- var Collapse = function (element, options) {
- this.$element = $(element)
- this.options = $.extend({}, $.fn.collapse.defaults, options)
-
- if (this.options.parent) {
- this.$parent = $(this.options.parent)
- }
-
- this.options.toggle && this.toggle()
- }
-
- Collapse.prototype = {
-
- constructor: Collapse
-
- , dimension: function () {
- var hasWidth = this.$element.hasClass('width')
- return hasWidth ? 'width' : 'height'
- }
-
- , show: function () {
- var dimension
- , scroll
- , actives
- , hasData
-
- if (this.transitioning) return
-
- dimension = this.dimension()
- scroll = $.camelCase(['scroll', dimension].join('-'))
- actives = this.$parent && this.$parent.find('> .accordion-group > .in')
-
- if (actives && actives.length) {
- hasData = actives.data('collapse')
- if (hasData && hasData.transitioning) return
- actives.collapse('hide')
- hasData || actives.data('collapse', null)
- }
-
- this.$element[dimension](0)
- this.transition('addClass', $.Event('show'), 'shown')
- $.support.transition && this.$element[dimension](this.$element[0][scroll])
- }
-
- , hide: function () {
- var dimension
- if (this.transitioning) return
- dimension = this.dimension()
- this.reset(this.$element[dimension]())
- this.transition('removeClass', $.Event('hide'), 'hidden')
- this.$element[dimension](0)
- }
-
- , reset: function (size) {
- var dimension = this.dimension()
-
- this.$element
- .removeClass('collapse')
- [dimension](size || 'auto')
- [0].offsetWidth
-
- this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
-
- return this
- }
-
- , transition: function (method, startEvent, completeEvent) {
- var that = this
- , complete = function () {
- if (startEvent.type == 'show') that.reset()
- that.transitioning = 0
- that.$element.trigger(completeEvent)
- }
-
- this.$element.trigger(startEvent)
-
- if (startEvent.isDefaultPrevented()) return
-
- this.transitioning = 1
-
- this.$element[method]('in')
-
- $.support.transition && this.$element.hasClass('collapse') ?
- this.$element.one($.support.transition.end, complete) :
- complete()
- }
-
- , toggle: function () {
- this[this.$element.hasClass('in') ? 'hide' : 'show']()
- }
-
- }
-
-
- /* COLLAPSIBLE PLUGIN DEFINITION
- * ============================== */
-
- $.fn.collapse = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('collapse')
- , options = typeof option == 'object' && option
- if (!data) $this.data('collapse', (data = new Collapse(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.collapse.defaults = {
- toggle: true
- }
-
- $.fn.collapse.Constructor = Collapse
-
-
- /* COLLAPSIBLE DATA-API
- * ==================== */
-
- $(function () {
- $('body').on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
- var $this = $(this), href
- , target = $this.attr('data-target')
- || e.preventDefault()
- || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
- , option = $(target).data('collapse') ? 'toggle' : $this.data()
- $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
- $(target).collapse(option)
- })
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-dropdown.js b/docs/static/js/bootstrap-dropdown.js
deleted file mode 100755
index 42370dfb..00000000
--- a/docs/static/js/bootstrap-dropdown.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/* ============================================================
- * bootstrap-dropdown.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#dropdowns
- * ============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* DROPDOWN CLASS DEFINITION
- * ========================= */
-
- var toggle = '[data-toggle=dropdown]'
- , Dropdown = function (element) {
- var $el = $(element).on('click.dropdown.data-api', this.toggle)
- $('html').on('click.dropdown.data-api', function () {
- $el.parent().removeClass('open')
- })
- }
-
- Dropdown.prototype = {
-
- constructor: Dropdown
-
- , toggle: function (e) {
- var $this = $(this)
- , $parent
- , isActive
-
- if ($this.is('.disabled, :disabled')) return
-
- $parent = getParent($this)
-
- isActive = $parent.hasClass('open')
-
- clearMenus()
-
- if (!isActive) {
- $parent.toggleClass('open')
- $this.focus()
- }
-
- return false
- }
-
- , keydown: function (e) {
- var $this
- , $items
- , $active
- , $parent
- , isActive
- , index
-
- if (!/(38|40|27)/.test(e.keyCode)) return
-
- $this = $(this)
-
- e.preventDefault()
- e.stopPropagation()
-
- if ($this.is('.disabled, :disabled')) return
-
- $parent = getParent($this)
-
- isActive = $parent.hasClass('open')
-
- if (!isActive || (isActive && e.keyCode == 27)) return $this.click()
-
- $items = $('[role=menu] li:not(.divider) a', $parent)
-
- if (!$items.length) return
-
- index = $items.index($items.filter(':focus'))
-
- if (e.keyCode == 38 && index > 0) index-- // up
- if (e.keyCode == 40 && index < $items.length - 1) index++ // down
- if (!~index) index = 0
-
- $items
- .eq(index)
- .focus()
- }
-
- }
-
- function clearMenus() {
- getParent($(toggle))
- .removeClass('open')
- }
-
- function getParent($this) {
- var selector = $this.attr('data-target')
- , $parent
-
- if (!selector) {
- selector = $this.attr('href')
- selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
- }
-
- $parent = $(selector)
- $parent.length || ($parent = $this.parent())
-
- return $parent
- }
-
-
- /* DROPDOWN PLUGIN DEFINITION
- * ========================== */
-
- $.fn.dropdown = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('dropdown')
- if (!data) $this.data('dropdown', (data = new Dropdown(this)))
- if (typeof option == 'string') data[option].call($this)
- })
- }
-
- $.fn.dropdown.Constructor = Dropdown
-
-
- /* APPLY TO STANDARD DROPDOWN ELEMENTS
- * =================================== */
-
- $(function () {
- $('html')
- .on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus)
- $('body')
- .on('click.dropdown touchstart.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
- .on('click.dropdown.data-api touchstart.dropdown.data-api' , toggle, Dropdown.prototype.toggle)
- .on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown)
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-modal.js b/docs/static/js/bootstrap-modal.js
deleted file mode 100755
index f1622b1c..00000000
--- a/docs/static/js/bootstrap-modal.js
+++ /dev/null
@@ -1,239 +0,0 @@
-/* =========================================================
- * bootstrap-modal.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#modals
- * =========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================= */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* MODAL CLASS DEFINITION
- * ====================== */
-
- var Modal = function (element, options) {
- this.options = options
- this.$element = $(element)
- .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
- this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
- }
-
- Modal.prototype = {
-
- constructor: Modal
-
- , toggle: function () {
- return this[!this.isShown ? 'show' : 'hide']()
- }
-
- , show: function () {
- var that = this
- , e = $.Event('show')
-
- this.$element.trigger(e)
-
- if (this.isShown || e.isDefaultPrevented()) return
-
- $('body').addClass('modal-open')
-
- this.isShown = true
-
- this.escape()
-
- this.backdrop(function () {
- var transition = $.support.transition && that.$element.hasClass('fade')
-
- if (!that.$element.parent().length) {
- that.$element.appendTo(document.body) //don't move modals dom position
- }
-
- that.$element
- .show()
-
- if (transition) {
- that.$element[0].offsetWidth // force reflow
- }
-
- that.$element
- .addClass('in')
- .attr('aria-hidden', false)
- .focus()
-
- that.enforceFocus()
-
- transition ?
- that.$element.one($.support.transition.end, function () { that.$element.trigger('shown') }) :
- that.$element.trigger('shown')
-
- })
- }
-
- , hide: function (e) {
- e && e.preventDefault()
-
- var that = this
-
- e = $.Event('hide')
-
- this.$element.trigger(e)
-
- if (!this.isShown || e.isDefaultPrevented()) return
-
- this.isShown = false
-
- $('body').removeClass('modal-open')
-
- this.escape()
-
- $(document).off('focusin.modal')
-
- this.$element
- .removeClass('in')
- .attr('aria-hidden', true)
-
- $.support.transition && this.$element.hasClass('fade') ?
- this.hideWithTransition() :
- this.hideModal()
- }
-
- , enforceFocus: function () {
- var that = this
- $(document).on('focusin.modal', function (e) {
- if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
- that.$element.focus()
- }
- })
- }
-
- , escape: function () {
- var that = this
- if (this.isShown && this.options.keyboard) {
- this.$element.on('keyup.dismiss.modal', function ( e ) {
- e.which == 27 && that.hide()
- })
- } else if (!this.isShown) {
- this.$element.off('keyup.dismiss.modal')
- }
- }
-
- , hideWithTransition: function () {
- var that = this
- , timeout = setTimeout(function () {
- that.$element.off($.support.transition.end)
- that.hideModal()
- }, 500)
-
- this.$element.one($.support.transition.end, function () {
- clearTimeout(timeout)
- that.hideModal()
- })
- }
-
- , hideModal: function (that) {
- this.$element
- .hide()
- .trigger('hidden')
-
- this.backdrop()
- }
-
- , removeBackdrop: function () {
- this.$backdrop.remove()
- this.$backdrop = null
- }
-
- , backdrop: function (callback) {
- var that = this
- , animate = this.$element.hasClass('fade') ? 'fade' : ''
-
- if (this.isShown && this.options.backdrop) {
- var doAnimate = $.support.transition && animate
-
- this.$backdrop = $('')
- .appendTo(document.body)
-
- if (this.options.backdrop != 'static') {
- this.$backdrop.click($.proxy(this.hide, this))
- }
-
- if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
-
- this.$backdrop.addClass('in')
-
- doAnimate ?
- this.$backdrop.one($.support.transition.end, callback) :
- callback()
-
- } else if (!this.isShown && this.$backdrop) {
- this.$backdrop.removeClass('in')
-
- $.support.transition && this.$element.hasClass('fade')?
- this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) :
- this.removeBackdrop()
-
- } else if (callback) {
- callback()
- }
- }
- }
-
-
- /* MODAL PLUGIN DEFINITION
- * ======================= */
-
- $.fn.modal = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('modal')
- , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
- if (!data) $this.data('modal', (data = new Modal(this, options)))
- if (typeof option == 'string') data[option]()
- else if (options.show) data.show()
- })
- }
-
- $.fn.modal.defaults = {
- backdrop: true
- , keyboard: true
- , show: true
- }
-
- $.fn.modal.Constructor = Modal
-
-
- /* MODAL DATA-API
- * ============== */
-
- $(function () {
- $('body').on('click.modal.data-api', '[data-toggle="modal"]', function ( e ) {
- var $this = $(this)
- , href = $this.attr('href')
- , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
- , option = $target.data('modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
-
- e.preventDefault()
-
- $target
- .modal(option)
- .one('hide', function () {
- $this.focus()
- })
- })
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-popover.js b/docs/static/js/bootstrap-popover.js
deleted file mode 100755
index 94137228..00000000
--- a/docs/static/js/bootstrap-popover.js
+++ /dev/null
@@ -1,103 +0,0 @@
-/* ===========================================================
- * bootstrap-popover.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#popovers
- * ===========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * =========================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* POPOVER PUBLIC CLASS DEFINITION
- * =============================== */
-
- var Popover = function (element, options) {
- this.init('popover', element, options)
- }
-
-
- /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
- ========================================== */
-
- Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
-
- constructor: Popover
-
- , setContent: function () {
- var $tip = this.tip()
- , title = this.getTitle()
- , content = this.getContent()
-
- $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
- $tip.find('.popover-content > *')[this.options.html ? 'html' : 'text'](content)
-
- $tip.removeClass('fade top bottom left right in')
- }
-
- , hasContent: function () {
- return this.getTitle() || this.getContent()
- }
-
- , getContent: function () {
- var content
- , $e = this.$element
- , o = this.options
-
- content = $e.attr('data-content')
- || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
-
- return content
- }
-
- , tip: function () {
- if (!this.$tip) {
- this.$tip = $(this.options.template)
- }
- return this.$tip
- }
-
- , destroy: function () {
- this.hide().$element.off('.' + this.type).removeData(this.type)
- }
-
- })
-
-
- /* POPOVER PLUGIN DEFINITION
- * ======================= */
-
- $.fn.popover = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('popover')
- , options = typeof option == 'object' && option
- if (!data) $this.data('popover', (data = new Popover(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.popover.Constructor = Popover
-
- $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
- placement: 'right'
- , trigger: 'click'
- , content: ''
- , template: '
'
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-scrollspy.js b/docs/static/js/bootstrap-scrollspy.js
deleted file mode 100755
index e740ac01..00000000
--- a/docs/static/js/bootstrap-scrollspy.js
+++ /dev/null
@@ -1,151 +0,0 @@
-/* =============================================================
- * bootstrap-scrollspy.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#scrollspy
- * =============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* SCROLLSPY CLASS DEFINITION
- * ========================== */
-
- function ScrollSpy(element, options) {
- var process = $.proxy(this.process, this)
- , $element = $(element).is('body') ? $(window) : $(element)
- , href
- this.options = $.extend({}, $.fn.scrollspy.defaults, options)
- this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
- this.selector = (this.options.target
- || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
- || '') + ' .nav li > a'
- this.$body = $('body')
- this.refresh()
- this.process()
- }
-
- ScrollSpy.prototype = {
-
- constructor: ScrollSpy
-
- , refresh: function () {
- var self = this
- , $targets
-
- this.offsets = $([])
- this.targets = $([])
-
- $targets = this.$body
- .find(this.selector)
- .map(function () {
- var $el = $(this)
- , href = $el.data('target') || $el.attr('href')
- , $href = /^#\w/.test(href) && $(href)
- return ( $href
- && $href.length
- && [[ $href.position().top, href ]] ) || null
- })
- .sort(function (a, b) { return a[0] - b[0] })
- .each(function () {
- self.offsets.push(this[0])
- self.targets.push(this[1])
- })
- }
-
- , process: function () {
- var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
- , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
- , maxScroll = scrollHeight - this.$scrollElement.height()
- , offsets = this.offsets
- , targets = this.targets
- , activeTarget = this.activeTarget
- , i
-
- if (scrollTop >= maxScroll) {
- return activeTarget != (i = targets.last()[0])
- && this.activate ( i )
- }
-
- for (i = offsets.length; i--;) {
- activeTarget != targets[i]
- && scrollTop >= offsets[i]
- && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
- && this.activate( targets[i] )
- }
- }
-
- , activate: function (target) {
- var active
- , selector
-
- this.activeTarget = target
-
- $(this.selector)
- .parent('.active')
- .removeClass('active')
-
- selector = this.selector
- + '[data-target="' + target + '"],'
- + this.selector + '[href="' + target + '"]'
-
- active = $(selector)
- .parent('li')
- .addClass('active')
-
- if (active.parent('.dropdown-menu').length) {
- active = active.closest('li.dropdown').addClass('active')
- }
-
- active.trigger('activate')
- }
-
- }
-
-
- /* SCROLLSPY PLUGIN DEFINITION
- * =========================== */
-
- $.fn.scrollspy = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('scrollspy')
- , options = typeof option == 'object' && option
- if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.scrollspy.Constructor = ScrollSpy
-
- $.fn.scrollspy.defaults = {
- offset: 10
- }
-
-
- /* SCROLLSPY DATA-API
- * ================== */
-
- $(window).on('load', function () {
- $('[data-spy="scroll"]').each(function () {
- var $spy = $(this)
- $spy.scrollspy($spy.data())
- })
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-tab.js b/docs/static/js/bootstrap-tab.js
deleted file mode 100755
index 070deb8f..00000000
--- a/docs/static/js/bootstrap-tab.js
+++ /dev/null
@@ -1,135 +0,0 @@
-/* ========================================================
- * bootstrap-tab.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#tabs
- * ========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ======================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* TAB CLASS DEFINITION
- * ==================== */
-
- var Tab = function (element) {
- this.element = $(element)
- }
-
- Tab.prototype = {
-
- constructor: Tab
-
- , show: function () {
- var $this = this.element
- , $ul = $this.closest('ul:not(.dropdown-menu)')
- , selector = $this.attr('data-target')
- , previous
- , $target
- , e
-
- if (!selector) {
- selector = $this.attr('href')
- selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
- }
-
- if ( $this.parent('li').hasClass('active') ) return
-
- previous = $ul.find('.active a').last()[0]
-
- e = $.Event('show', {
- relatedTarget: previous
- })
-
- $this.trigger(e)
-
- if (e.isDefaultPrevented()) return
-
- $target = $(selector)
-
- this.activate($this.parent('li'), $ul)
- this.activate($target, $target.parent(), function () {
- $this.trigger({
- type: 'shown'
- , relatedTarget: previous
- })
- })
- }
-
- , activate: function ( element, container, callback) {
- var $active = container.find('> .active')
- , transition = callback
- && $.support.transition
- && $active.hasClass('fade')
-
- function next() {
- $active
- .removeClass('active')
- .find('> .dropdown-menu > .active')
- .removeClass('active')
-
- element.addClass('active')
-
- if (transition) {
- element[0].offsetWidth // reflow for transition
- element.addClass('in')
- } else {
- element.removeClass('fade')
- }
-
- if ( element.parent('.dropdown-menu') ) {
- element.closest('li.dropdown').addClass('active')
- }
-
- callback && callback()
- }
-
- transition ?
- $active.one($.support.transition.end, next) :
- next()
-
- $active.removeClass('in')
- }
- }
-
-
- /* TAB PLUGIN DEFINITION
- * ===================== */
-
- $.fn.tab = function ( option ) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('tab')
- if (!data) $this.data('tab', (data = new Tab(this)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.tab.Constructor = Tab
-
-
- /* TAB DATA-API
- * ============ */
-
- $(function () {
- $('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
- e.preventDefault()
- $(this).tab('show')
- })
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-tooltip.js b/docs/static/js/bootstrap-tooltip.js
deleted file mode 100755
index ed628853..00000000
--- a/docs/static/js/bootstrap-tooltip.js
+++ /dev/null
@@ -1,275 +0,0 @@
-/* ===========================================================
- * bootstrap-tooltip.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#tooltips
- * Inspired by the original jQuery.tipsy by Jason Frame
- * ===========================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
- "use strict"; // jshint ;_;
-
-
- /* TOOLTIP PUBLIC CLASS DEFINITION
- * =============================== */
-
- var Tooltip = function (element, options) {
- this.init('tooltip', element, options)
- }
-
- Tooltip.prototype = {
-
- constructor: Tooltip
-
- , init: function (type, element, options) {
- var eventIn
- , eventOut
-
- this.type = type
- this.$element = $(element)
- this.options = this.getOptions(options)
- this.enabled = true
-
- if (this.options.trigger == 'click') {
- this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
- } else if (this.options.trigger != 'manual') {
- eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'
- eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'
- this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
- this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
- }
-
- this.options.selector ?
- (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
- this.fixTitle()
- }
-
- , getOptions: function (options) {
- options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data())
-
- if (options.delay && typeof options.delay == 'number') {
- options.delay = {
- show: options.delay
- , hide: options.delay
- }
- }
-
- return options
- }
-
- , enter: function (e) {
- var self = $(e.currentTarget)[this.type](this._options).data(this.type)
-
- if (!self.options.delay || !self.options.delay.show) return self.show()
-
- clearTimeout(this.timeout)
- self.hoverState = 'in'
- this.timeout = setTimeout(function() {
- if (self.hoverState == 'in') self.show()
- }, self.options.delay.show)
- }
-
- , leave: function (e) {
- var self = $(e.currentTarget)[this.type](this._options).data(this.type)
-
- if (this.timeout) clearTimeout(this.timeout)
- if (!self.options.delay || !self.options.delay.hide) return self.hide()
-
- self.hoverState = 'out'
- this.timeout = setTimeout(function() {
- if (self.hoverState == 'out') self.hide()
- }, self.options.delay.hide)
- }
-
- , show: function () {
- var $tip
- , inside
- , pos
- , actualWidth
- , actualHeight
- , placement
- , tp
-
- if (this.hasContent() && this.enabled) {
- $tip = this.tip()
- this.setContent()
-
- if (this.options.animation) {
- $tip.addClass('fade')
- }
-
- placement = typeof this.options.placement == 'function' ?
- this.options.placement.call(this, $tip[0], this.$element[0]) :
- this.options.placement
-
- inside = /in/.test(placement)
-
- $tip
- .remove()
- .css({ top: 0, left: 0, display: 'block' })
- .appendTo(inside ? this.$element : document.body)
-
- pos = this.getPosition(inside)
-
- actualWidth = $tip[0].offsetWidth
- actualHeight = $tip[0].offsetHeight
-
- switch (inside ? placement.split(' ')[1] : placement) {
- case 'bottom':
- tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}
- break
- case 'top':
- tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}
- break
- case 'left':
- tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}
- break
- case 'right':
- tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
- break
- }
-
- $tip
- .css(tp)
- .addClass(placement)
- .addClass('in')
- }
- }
-
- , setContent: function () {
- var $tip = this.tip()
- , title = this.getTitle()
-
- $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
- $tip.removeClass('fade in top bottom left right')
- }
-
- , hide: function () {
- var that = this
- , $tip = this.tip()
-
- $tip.removeClass('in')
-
- function removeWithAnimation() {
- var timeout = setTimeout(function () {
- $tip.off($.support.transition.end).remove()
- }, 500)
-
- $tip.one($.support.transition.end, function () {
- clearTimeout(timeout)
- $tip.remove()
- })
- }
-
- $.support.transition && this.$tip.hasClass('fade') ?
- removeWithAnimation() :
- $tip.remove()
-
- return this
- }
-
- , fixTitle: function () {
- var $e = this.$element
- if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
- $e.attr('data-original-title', $e.attr('title') || '').removeAttr('title')
- }
- }
-
- , hasContent: function () {
- return this.getTitle()
- }
-
- , getPosition: function (inside) {
- return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), {
- width: this.$element[0].offsetWidth
- , height: this.$element[0].offsetHeight
- })
- }
-
- , getTitle: function () {
- var title
- , $e = this.$element
- , o = this.options
-
- title = $e.attr('data-original-title')
- || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
-
- return title
- }
-
- , tip: function () {
- return this.$tip = this.$tip || $(this.options.template)
- }
-
- , validate: function () {
- if (!this.$element[0].parentNode) {
- this.hide()
- this.$element = null
- this.options = null
- }
- }
-
- , enable: function () {
- this.enabled = true
- }
-
- , disable: function () {
- this.enabled = false
- }
-
- , toggleEnabled: function () {
- this.enabled = !this.enabled
- }
-
- , toggle: function () {
- this[this.tip().hasClass('in') ? 'hide' : 'show']()
- }
-
- , destroy: function () {
- this.hide().$element.off('.' + this.type).removeData(this.type)
- }
-
- }
-
-
- /* TOOLTIP PLUGIN DEFINITION
- * ========================= */
-
- $.fn.tooltip = function ( option ) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('tooltip')
- , options = typeof option == 'object' && option
- if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.tooltip.Constructor = Tooltip
-
- $.fn.tooltip.defaults = {
- animation: true
- , placement: 'top'
- , selector: false
- , template: '
'
- , trigger: 'hover'
- , title: ''
- , delay: 0
- , html: true
- }
-
-}(window.jQuery);
diff --git a/docs/static/js/bootstrap-transition.js b/docs/static/js/bootstrap-transition.js
deleted file mode 100755
index fedc90a8..00000000
--- a/docs/static/js/bootstrap-transition.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/* ===================================================
- * bootstrap-transition.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#transitions
- * ===================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ========================================================== */
-
-
-!function ($) {
-
- $(function () {
-
- "use strict"; // jshint ;_;
-
-
- /* CSS TRANSITION SUPPORT (http://www.modernizr.com/)
- * ======================================================= */
-
- $.support.transition = (function () {
-
- var transitionEnd = (function () {
-
- var el = document.createElement('bootstrap')
- , transEndEventNames = {
- 'WebkitTransition' : 'webkitTransitionEnd'
- , 'MozTransition' : 'transitionend'
- , 'OTransition' : 'oTransitionEnd otransitionend'
- , 'transition' : 'transitionend'
- }
- , name
-
- for (name in transEndEventNames){
- if (el.style[name] !== undefined) {
- return transEndEventNames[name]
- }
- }
-
- }())
-
- return transitionEnd && {
- end: transitionEnd
- }
-
- })()
-
- })
-
-}(window.jQuery);
\ No newline at end of file
diff --git a/docs/static/js/bootstrap-typeahead.js b/docs/static/js/bootstrap-typeahead.js
deleted file mode 100755
index c2ccdea2..00000000
--- a/docs/static/js/bootstrap-typeahead.js
+++ /dev/null
@@ -1,300 +0,0 @@
-/* =============================================================
- * bootstrap-typeahead.js v2.1.1
- * http://twitter.github.com/bootstrap/javascript.html#typeahead
- * =============================================================
- * Copyright 2012 Twitter, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============================================================ */
-
-
-!function($){
-
- "use strict"; // jshint ;_;
-
-
- /* TYPEAHEAD PUBLIC CLASS DEFINITION
- * ================================= */
-
- var Typeahead = function (element, options) {
- this.$element = $(element)
- this.options = $.extend({}, $.fn.typeahead.defaults, options)
- this.matcher = this.options.matcher || this.matcher
- this.sorter = this.options.sorter || this.sorter
- this.highlighter = this.options.highlighter || this.highlighter
- this.updater = this.options.updater || this.updater
- this.$menu = $(this.options.menu).appendTo('body')
- this.source = this.options.source
- this.shown = false
- this.listen()
- }
-
- Typeahead.prototype = {
-
- constructor: Typeahead
-
- , select: function () {
- var val = this.$menu.find('.active').attr('data-value')
- this.$element
- .val(this.updater(val))
- .change()
- return this.hide()
- }
-
- , updater: function (item) {
- return item
- }
-
- , show: function () {
- var pos = $.extend({}, this.$element.offset(), {
- height: this.$element[0].offsetHeight
- })
-
- this.$menu.css({
- top: pos.top + pos.height
- , left: pos.left
- })
-
- this.$menu.show()
- this.shown = true
- return this
- }
-
- , hide: function () {
- this.$menu.hide()
- this.shown = false
- return this
- }
-
- , lookup: function (event) {
- var items
-
- this.query = this.$element.val()
-
- if (!this.query || this.query.length < this.options.minLength) {
- return this.shown ? this.hide() : this
- }
-
- items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source
-
- return items ? this.process(items) : this
- }
-
- , process: function (items) {
- var that = this
-
- items = $.grep(items, function (item) {
- return that.matcher(item)
- })
-
- items = this.sorter(items)
-
- if (!items.length) {
- return this.shown ? this.hide() : this
- }
-
- return this.render(items.slice(0, this.options.items)).show()
- }
-
- , matcher: function (item) {
- return ~item.toLowerCase().indexOf(this.query.toLowerCase())
- }
-
- , sorter: function (items) {
- var beginswith = []
- , caseSensitive = []
- , caseInsensitive = []
- , item
-
- while (item = items.shift()) {
- if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
- else if (~item.indexOf(this.query)) caseSensitive.push(item)
- else caseInsensitive.push(item)
- }
-
- return beginswith.concat(caseSensitive, caseInsensitive)
- }
-
- , highlighter: function (item) {
- var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
- return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
- return '' + match + ''
- })
- }
-
- , render: function (items) {
- var that = this
-
- items = $(items).map(function (i, item) {
- i = $(that.options.item).attr('data-value', item)
- i.find('a').html(that.highlighter(item))
- return i[0]
- })
-
- items.first().addClass('active')
- this.$menu.html(items)
- return this
- }
-
- , next: function (event) {
- var active = this.$menu.find('.active').removeClass('active')
- , next = active.next()
-
- if (!next.length) {
- next = $(this.$menu.find('li')[0])
- }
-
- next.addClass('active')
- }
-
- , prev: function (event) {
- var active = this.$menu.find('.active').removeClass('active')
- , prev = active.prev()
-
- if (!prev.length) {
- prev = this.$menu.find('li').last()
- }
-
- prev.addClass('active')
- }
-
- , listen: function () {
- this.$element
- .on('blur', $.proxy(this.blur, this))
- .on('keypress', $.proxy(this.keypress, this))
- .on('keyup', $.proxy(this.keyup, this))
-
- if ($.browser.chrome || $.browser.webkit || $.browser.msie) {
- this.$element.on('keydown', $.proxy(this.keydown, this))
- }
-
- this.$menu
- .on('click', $.proxy(this.click, this))
- .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
- }
-
- , move: function (e) {
- if (!this.shown) return
-
- switch(e.keyCode) {
- case 9: // tab
- case 13: // enter
- case 27: // escape
- e.preventDefault()
- break
-
- case 38: // up arrow
- e.preventDefault()
- this.prev()
- break
-
- case 40: // down arrow
- e.preventDefault()
- this.next()
- break
- }
-
- e.stopPropagation()
- }
-
- , keydown: function (e) {
- this.suppressKeyPressRepeat = !~$.inArray(e.keyCode, [40,38,9,13,27])
- this.move(e)
- }
-
- , keypress: function (e) {
- if (this.suppressKeyPressRepeat) return
- this.move(e)
- }
-
- , keyup: function (e) {
- switch(e.keyCode) {
- case 40: // down arrow
- case 38: // up arrow
- break
-
- case 9: // tab
- case 13: // enter
- if (!this.shown) return
- this.select()
- break
-
- case 27: // escape
- if (!this.shown) return
- this.hide()
- break
-
- default:
- this.lookup()
- }
-
- e.stopPropagation()
- e.preventDefault()
- }
-
- , blur: function (e) {
- var that = this
- setTimeout(function () { that.hide() }, 150)
- }
-
- , click: function (e) {
- e.stopPropagation()
- e.preventDefault()
- this.select()
- }
-
- , mouseenter: function (e) {
- this.$menu.find('.active').removeClass('active')
- $(e.currentTarget).addClass('active')
- }
-
- }
-
-
- /* TYPEAHEAD PLUGIN DEFINITION
- * =========================== */
-
- $.fn.typeahead = function (option) {
- return this.each(function () {
- var $this = $(this)
- , data = $this.data('typeahead')
- , options = typeof option == 'object' && option
- if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
- if (typeof option == 'string') data[option]()
- })
- }
-
- $.fn.typeahead.defaults = {
- source: []
- , items: 8
- , menu: '
',minLength:1},a.fn.typeahead.Constructor=b,a(function(){a("body").on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(b){var c=a(this);if(c.data("typeahead"))return;b.preventDefault(),c.typeahead(c.data())})})}(window.jQuery)
\ No newline at end of file
diff --git a/docs/template.html b/docs/template.html
index fbd30159..854a8100 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -91,9 +91,10 @@
+
-
-
+
+
{{ toc }}
@@ -103,6 +104,7 @@
{{ content }}
+
-
-
-
+
-
-
+
+
+
+
+
--
cgit v1.2.3
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')
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')
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')
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')
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 ++++----
docs/index.md | 4 +-
docs/template.html | 2 +-
docs/topics/rest-framework-2-announcement.md | 88 ++++++++++++++++++++++++++++
4 files changed, 104 insertions(+), 13 deletions(-)
create mode 100644 docs/topics/rest-framework-2-announcement.md
(limited to 'docs')
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
diff --git a/docs/index.md b/docs/index.md
index f66ba7f4..a75dbc58 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -103,7 +103,7 @@ General guides to using REST framework.
* [The Browsable API][browsableapi]
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
* [Contributing to REST framework][contributing]
-* [2.0 Migration Guide][migration]
+* [2.0 Announcement][rest-framework-2-announcement]
* [Release Notes][release-notes]
* [Credits][credits]
@@ -189,7 +189,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[browsableapi]: topics/browsable-api.md
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
[contributing]: topics/contributing.md
-[migration]: topics/migration.md
+[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
[release-notes]: topics/release-notes.md
[credits]: topics/credits.md
diff --git a/docs/template.html b/docs/template.html
index 56c5d832..91a7a731 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -93,7 +93,7 @@
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
new file mode 100644
index 00000000..98e66228
--- /dev/null
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -0,0 +1,88 @@
+# Django REST framework 2
+
+What it is, and why you should care
+
+> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
+>
+> — [Roy Fielding][cite]
+
+REST framework 2 is an almost complete reworking of the original framework, which comprehensivly addresses some of the original design issues.
+
+Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.
+
+This article is intended to give you a flavor of what REST framework 2 is, and why you might want to give it a try.
+
+## User feedback
+
+Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…
+
+"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1]
+
+"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2]
+
+"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3]
+
+Sounds good, right? Let's get into some details...
+
+## Serialization
+
+REST framework 2 includes a totally re-worked serialization engine, that was initially intended as a replacement for Django's existing inflexible fixture serialization, and which meets the following design goals:
+
+* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API.
+* Structural concerns are decoupled from encoding concerns.
+* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
+* Validation that can be mapped to obvious and comprehensive error responses.
+* Serializers that support both nested, flat, and partially-nested representations.
+* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
+
+Mapping between the internal state of the system and external representations of that state is the core concern of building Web APIs. Designing serializers that allow the developer to do so in a flexible and obvious way is a deceptively difficult design task, and with the new serialization API we think we've pretty much nailed it.
+
+## Generic views
+
+When REST framework was initially released at the start of 2011, the current Django release was version 1.2. REST framework included a backport of Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations.
+
+With the new release the generic views in REST framework now tie in with Django's generic views. The end result is that framework is clean, lightweight and easy to use.
+
+## Requests, Responses & Views
+
+REST framework 2 includes `Request` and `Response` classes, than are used in place of Django's existing `HttpRequest` and `HttpResponse` classes. Doing so allows logic such as parsing the incoming request or rendering the outgoing response to be supported transparently by the framework.
+
+The `Request`/`Response` approach leads to a much cleaner API, less logic in the view itself, and a simple, obvious request-response cycle.
+
+REST framework 2 also allows you to work with both function-based and class-based views. For simple API views all you need is a single `@api_view` decorator, and you're good to go.
+
+
+## API Design
+
+Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independantly of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
+
+## Documentation
+
+As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
+
+In the author's opinion, using `markdown` for documentation is a much better option that `rst`. It is intuitive and readable, and there is great tooling available, such as the [Mou][mou] editor for Mac OS X, which makes it easy and plesant to work.
+
+We're really pleased with how the docs style looks - it's simple and clean, and the docs build much more quickly than with the previous sphinx setup. We'll miss being able to use the wonderful [Read the Docs][readthedocs] service, but we think it's a trade-off worth making.
+
+Developing REST framework's documentation builder into a fully-fledged reusable project is something that we have planned for a future date.
+
+## The Browseable API
+
+Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.
+
+Browseable Web APIs are easier to work with, visualize and debug, and generally makes it easier and more frictionless to inspect and work with.
+
+With REST framework 2, the browseable API gets a snazzy new bootstrap-based theme that looks great and is even nicer to work with.
+
+There are also some functionality improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
+
+## Summary
+
+In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
+
+[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724
+[quote1]: https://twitter.com/kobutsu/status/261689665952833536
+[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J
+[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ
+[mou]: http://mouapp.com/
+[readthedocs]: https://readthedocs.org/
--
cgit v1.2.3
From 51a64019260d99e3c615b407353e344cf615da1e Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sat, 27 Oct 2012 18:47:17 +0100
Subject: Added @madisvain. Thanks!
---
docs/topics/credits.md | 2 ++
1 file changed, 2 insertions(+)
(limited to 'docs')
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index 27a56326..a317afde 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -49,6 +49,7 @@ The following people have helped make REST framework great.
* Tomi Pajunen - [eofs]
* Rob Dobson - [rdobson]
* Daniel Vaca Araujo - [diviei]
+* Madis Väin - [madisvain]
Many thanks to everyone who's contributed to the project.
@@ -129,3 +130,4 @@ To contact the author directly:
[eofs]: https://github.com/eofs
[rdobson]: https://github.com/rdobson
[diviei]: https://github.com/diviei
+[madisvain]: https://github.com/madisvain
--
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')
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')
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 fde79376f323708d9f7b80ee830fe63060fb335f Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 19:25:51 +0000
Subject: Pastebin tutorial
---
docs/tutorial/1-serialization.md | 180 ++++++++++++--------
docs/tutorial/2-requests-and-responses.md | 45 +++--
docs/tutorial/3-class-based-views.md | 88 +++++-----
docs/tutorial/4-authentication-and-permissions.md | 183 +++++++++++++++++++++
.../4-authentication-permissions-and-throttling.md | 5 -
.../5-relationships-and-hyperlinked-apis.md | 158 +++++++++++++++++-
6 files changed, 512 insertions(+), 147 deletions(-)
create mode 100644 docs/tutorial/4-authentication-and-permissions.md
delete mode 100644 docs/tutorial/4-authentication-permissions-and-throttling.md
(limited to 'docs')
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index d1ae0ba5..fc052202 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -2,7 +2,9 @@
## Introduction
-This tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together.
+This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
+
+The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
## Setting up a new environment
@@ -17,6 +19,7 @@ Now that we're inside a virtualenv environment, we can install our package requi
pip install django
pip install djangorestframework
+ pip install pygments # We'll be using this for the code highlighting
**Note:** To exit the virtualenv environment at any time, just type `deactivate`. For more information see the [virtualenv documentation][virtualenv].
@@ -30,8 +33,9 @@ To get started, let's create a new project to work with.
cd tutorial
Once that's done we can create an app that we'll use to create a simple Web API.
+We're going to create a project that
- python manage.py startapp blog
+ python manage.py startapp snippets
The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`.
@@ -46,32 +50,48 @@ The simplest way to get up and running will probably be to use an `sqlite3` data
}
}
-We'll also need to add our new `blog` app and the `rest_framework` app to `INSTALLED_APPS`.
+We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`.
INSTALLED_APPS = (
...
'rest_framework',
- 'blog'
+ 'snippets'
)
-We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our blog views.
+We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet views.
urlpatterns = patterns('',
- url(r'^', include('blog.urls')),
+ url(r'^', include('snippets.urls')),
)
Okay, we're ready to roll.
## Creating a model to work with
-For the purposes of this tutorial we're going to start by creating a simple `Comment` model that is used to store comments against a blog post. Go ahead and edit the `blog` app's `models.py` file.
+For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file.
from django.db import models
-
- class Comment(models.Model):
- email = models.EmailField()
- content = models.CharField(max_length=200)
+ from pygments.lexers import get_all_lexers
+ from pygments.styles import get_all_styles
+
+ LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()])
+ STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles()))
+
+
+ class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
+ title = models.CharField(max_length=100, default='')
+ code = models.TextField()
+ linenos = models.BooleanField(default=False)
+ language = models.CharField(choices=LANGUAGE_CHOICES,
+ default='python',
+ max_length=100)
+ style = models.CharField(choices=STYLE_CHOICES,
+ default='friendly',
+ max_length=100)
+
+ class Meta:
+ ordering = ('created',)
Don't forget to sync the database for the first time.
@@ -79,28 +99,40 @@ Don't forget to sync the database for the first time.
## Creating a Serializer class
-We're going to create a simple Web API that we can use to edit these comment objects with. The first thing we need is a way of serializing and deserializing the objects into representations such as `json`. We do this by declaring serializers that work very similarly to Django's forms. Create a file in the `blog` directory named `serializers.py` and add the following.
+The first thing we need to get started on our Web API is provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similarly to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following.
- from blog import models
+ from django.forms import widgets
from rest_framework import serializers
-
-
- class CommentSerializer(serializers.Serializer):
- id = serializers.IntegerField(readonly=True)
- email = serializers.EmailField()
- content = serializers.CharField(max_length=200)
- created = serializers.DateTimeField(readonly=True)
-
+ from snippets import models
+
+
+ class SnippetSerializer(serializers.Serializer):
+ pk = serializers.Field() # Note: `Field` is an untyped read-only field.
+ title = serializers.CharField(required=False,
+ max_length=100)
+ code = serializers.CharField(widget=widgets.Textarea,
+ max_length=100000)
+ linenos = serializers.BooleanField(required=False)
+ language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES,
+ default='python')
+ style = serializers.ChoiceField(choices=models.STYLE_CHOICES,
+ default='friendly')
+
def restore_object(self, attrs, instance=None):
"""
- Create or update a new comment instance.
+ Create or update a new snippet instance.
"""
if instance:
- instance.email = attrs['email']
- instance.content = attrs['content']
- instance.created = attrs['created']
+ # Update existing instance
+ instance.title = attrs['title']
+ instance.code = attrs['code']
+ instance.linenos = attrs['linenos']
+ instance.language = attrs['language']
+ instance.style = attrs['style']
return instance
- return models.Comment(**attrs)
+
+ # Create new instance
+ return models.Snippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
@@ -112,31 +144,27 @@ Before we go any further we'll familiarise ourselves with using our new Serializ
python manage.py shell
-Okay, once we've got a few imports out of the way, we'd better create a few comments to work with.
+Okay, once we've got a few imports out of the way, let's create a code snippet to work with.
- from blog.models import Comment
- from blog.serializers import CommentSerializer
+ from snippets.models import Snippet
+ from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
- c1 = Comment(email='leila@example.com', content='nothing to say')
- c2 = Comment(email='tom@example.com', content='foo bar')
- c3 = Comment(email='anna@example.com', content='LOLZ!')
- c1.save()
- c2.save()
- c3.save()
+ snippet = Snippet(code='print "hello, world"\n')
+ snippet.save()
-We've now got a few comment instances to play with. Let's take a look at serializing one of those instances.
+We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances.
- serializer = CommentSerializer(instance=c1)
+ serializer = SnippetSerializer(instance=snippet)
serializer.data
- # {'id': 1, 'email': u'leila@example.com', 'content': u'nothing to say', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774, tzinfo=)}
+ # {'pk': 1, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data)
content
- # '{"id": 1, "email": "leila@example.com", "content": "nothing to say", "created": "2012-08-22T16:20:09.822"}'
+ # '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into python native datatypes...
@@ -147,28 +175,45 @@ Deserialization is similar. First we parse a stream into python native datatype
...then we restore those native datatypes into to a fully populated object instance.
- serializer = CommentSerializer(data)
+ serializer = SnippetSerializer(data)
serializer.is_valid()
# True
serializer.object
- #
+ #
Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
-## Writing regular Django views using our Serializers
+## Using ModelSerializers
+
+Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep out code a bit more concise.
+
+In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
+
+Let's look at refactoring our serializer using the `ModelSerializer` class.
+Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` class.
+
+ class SnippetSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = models.Snippet
+ fields = ('pk', 'title', 'code', 'linenos', 'language', 'style')
+
+
+
+## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class.
+For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views.
+
We'll start off by creating a subclass of HttpResponse that we can use to render any data we return into `json`.
-Edit the `blog/views.py` file, and add the following.
+Edit the `snippet/views.py` file, and add the following.
- from blog.models import Comment
- from blog.serializers import CommentSerializer
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
-
+ from snippets.models import Snippet
+ from snippets.serializers import SnippetSerializer
class JSONResponse(HttpResponse):
"""
@@ -181,67 +226,65 @@ Edit the `blog/views.py` file, and add the following.
super(JSONResponse, self).__init__(content, **kwargs)
-The root of our API is going to be a view that supports listing all the existing comments, or creating a new comment.
+The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt
- def comment_root(request):
+ def snippet_list(request):
"""
- List all comments, or create a new comment.
+ List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
- comments = Comment.objects.all()
- serializer = CommentSerializer(instance=comments)
+ snippets = Snippet.objects.all()
+ serializer = SnippetSerializer(instance=snippets)
return JSONResponse(serializer.data)
elif request.method == 'POST':
data = JSONParser().parse(request)
- serializer = CommentSerializer(data)
+ serializer = SnippetSerializer(data)
if serializer.is_valid():
- comment = serializer.object
- comment.save()
+ serializer.save()
return JSONResponse(serializer.data, status=201)
else:
return JSONResponse(serializer.errors, status=400)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
-We'll also need a view which corresponds to an individual comment, and can be used to retrieve, update or delete the comment.
+We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
@csrf_exempt
- def comment_instance(request, pk):
+ def snippet_detail(request, pk):
"""
- Retrieve, update or delete a comment instance.
+ Retrieve, update or delete a code snippet.
"""
try:
- comment = Comment.objects.get(pk=pk)
- except Comment.DoesNotExist:
+ snippet = Snippet.objects.get(pk=pk)
+ except Snippet.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
- serializer = CommentSerializer(instance=comment)
+ serializer = SnippetSerializer(instance=snippet)
return JSONResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
- serializer = CommentSerializer(data, instance=comment)
+ serializer = SnippetSerializer(data, instance=snippet)
if serializer.is_valid():
- comment = serializer.object
- comment.save()
+ serializer.save()
return JSONResponse(serializer.data)
else:
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
- comment.delete()
+ snippet.delete()
return HttpResponse(status=204)
-Finally we need to wire these views up. Create the `blog/urls.py` file:
+Finally we need to wire these views up. Create the `snippet/urls.py` file:
from django.conf.urls import patterns, url
- urlpatterns = patterns('blog.views',
- url(r'^$', 'comment_root'),
- url(r'^(?P[0-9]+)$', 'comment_instance')
+ urlpatterns = patterns('snippets.views',
+ url(r'^snippet/$', 'snippet_list'),
+ url(r'^snippet/(?P[0-9]+)/$', 'snippet_detail')
)
It's worth noting that there's a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
@@ -260,5 +303,6 @@ Our API views don't do anything particularly special at the moment, beyond serve
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
+[quickstart]: quickstart.md
[virtualenv]: http://www.virtualenv.org/en/latest/index.html
[tut-2]: 2-requests-and-responses.md
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index fc37322a..76803d24 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -38,27 +38,27 @@ Okay, let's go ahead and start using these new components to write a few views.
We don't need our `JSONResponse` class anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.
- from blog.models import Comment
- from blog.serializers import CommentSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
+ from snippet.models import Snippet
+ from snippet.serializers import SnippetSerializer
+
@api_view(['GET', 'POST'])
- def comment_root(request):
+ def snippet_list(request):
"""
- List all comments, or create a new comment.
+ List all snippets, or create a new snippet.
"""
if request.method == 'GET':
- comments = Comment.objects.all()
- serializer = CommentSerializer(instance=comments)
+ snippets = Snippet.objects.all()
+ serializer = SnippetSerializer(instance=snippets)
return Response(serializer.data)
elif request.method == 'POST':
- serializer = CommentSerializer(request.DATA)
+ serializer = SnippetSerializer(request.DATA)
if serializer.is_valid():
- comment = serializer.object
- comment.save()
+ serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@@ -67,30 +67,29 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
@api_view(['GET', 'PUT', 'DELETE'])
- def comment_instance(request, pk):
+ def snippet_detail(request, pk):
"""
- Retrieve, update or delete a comment instance.
+ Retrieve, update or delete a snippet instance.
"""
try:
- comment = Comment.objects.get(pk=pk)
- except Comment.DoesNotExist:
+ snippet = Snippet.objects.get(pk=pk)
+ except Snippet.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
- serializer = CommentSerializer(instance=comment)
+ serializer = SnippetSerializer(instance=snippet)
return Response(serializer.data)
elif request.method == 'PUT':
- serializer = CommentSerializer(request.DATA, instance=comment)
+ serializer = SnippetSerializer(request.DATA, instance=snippet)
if serializer.is_valid():
- comment = serializer.object
- comment.save()
+ serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
- comment.delete()
+ snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
This should all feel very familiar - there's not a lot different to working with regular Django views.
@@ -103,20 +102,20 @@ To take advantage of the fact that our responses are no longer hardwired to a si
Start by adding a `format` keyword argument to both of the views, like so.
- def comment_root(request, format=None):
+ def snippet_list(request, format=None):
and
- def comment_instance(request, pk, format=None):
+ def snippet_detail(request, pk, format=None):
Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
- urlpatterns = patterns('blog.views',
- url(r'^$', 'comment_root'),
- url(r'^(?P[0-9]+)$', 'comment_instance')
+ urlpatterns = patterns('snippet.views',
+ url(r'^$', 'snippet_list'),
+ url(r'^(?P[0-9]+)$', 'snippet_detail')
)
urlpatterns = format_suffix_patterns(urlpatterns)
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index 0ee81ea3..3d58fe8e 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -6,61 +6,59 @@ We can also write our API views using class based views, rather than function ba
We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.
- from blog.models import Comment
- from blog.serializers import CommentSerializer
+ from snippet.models import Snippet
+ from snippet.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
- class CommentRoot(APIView):
+ class SnippetList(APIView):
"""
- List all comments, or create a new comment.
+ List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
- comments = Comment.objects.all()
- serializer = CommentSerializer(instance=comments)
+ snippets = Snippet.objects.all()
+ serializer = SnippetSerializer(instance=snippets)
return Response(serializer.data)
def post(self, request, format=None):
- serializer = CommentSerializer(request.DATA)
+ serializer = SnippetSerializer(request.DATA)
if serializer.is_valid():
- comment = serializer.object
- comment.save()
+ serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view.
- class CommentInstance(APIView):
+ class SnippetDetail(APIView):
"""
- Retrieve, update or delete a comment instance.
+ Retrieve, update or delete a snippet instance.
"""
def get_object(self, pk):
try:
- return Comment.objects.get(pk=pk)
- except Comment.DoesNotExist:
+ return Snippet.objects.get(pk=pk)
+ except Snippet.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
- comment = self.get_object(pk)
- serializer = CommentSerializer(instance=comment)
+ snippet = self.get_object(pk)
+ serializer = SnippetSerializer(instance=snippet)
return Response(serializer.data)
def put(self, request, pk, format=None):
- comment = self.get_object(pk)
- serializer = CommentSerializer(request.DATA, instance=comment)
+ snippet = self.get_object(pk)
+ serializer = SnippetSerializer(request.DATA, instance=snippet)
if serializer.is_valid():
- comment = serializer.object
- comment.save()
+ serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
- comment = self.get_object(pk)
- comment.delete()
+ snippet = self.get_object(pk)
+ snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
That's looking good. Again, it's still pretty similar to the function based view right now.
@@ -69,11 +67,11 @@ We'll also need to refactor our URLconf slightly now we're using class based vie
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
- from blogpost import views
+ from snippetpost import views
urlpatterns = patterns('',
- url(r'^$', views.CommentRoot.as_view()),
- url(r'^(?P[0-9]+)$', views.CommentInstance.as_view())
+ url(r'^$', views.SnippetList.as_view()),
+ url(r'^(?P[0-9]+)$', views.SnippetDetail.as_view())
)
urlpatterns = format_suffix_patterns(urlpatterns)
@@ -88,16 +86,16 @@ The create/retrieve/update/delete operations that we've been using so far are go
Let's take a look at how we can compose our views by using the mixin classes.
- from blog.models import Comment
- from blog.serializers import CommentSerializer
+ from snippet.models import Snippet
+ from snippet.serializers import SnippetSerializer
from rest_framework import mixins
from rest_framework import generics
- class CommentRoot(mixins.ListModelMixin,
+ class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.MultipleObjectBaseView):
- model = Comment
- serializer_class = CommentSerializer
+ model = Snippet
+ serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
@@ -109,12 +107,12 @@ We'll take a moment to examine exactly what's happening here - We're building ou
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
- class CommentInstance(mixins.RetrieveModelMixin,
- mixins.UpdateModelMixin,
- mixins.DestroyModelMixin,
- generics.SingleObjectBaseView):
- model = Comment
- serializer_class = CommentSerializer
+ class SnippetDetail(mixins.RetrieveModelMixin,
+ mixins.UpdateModelMixin,
+ mixins.DestroyModelMixin,
+ generics.SingleObjectBaseView):
+ model = Snippet
+ serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
@@ -131,23 +129,23 @@ Pretty similar. This time we're using the `SingleObjectBaseView` class to provi
Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use.
- from blog.models import Comment
- from blog.serializers import CommentSerializer
+ from snippet.models import Snippet
+ from snippet.serializers import SnippetSerializer
from rest_framework import generics
- class CommentRoot(generics.ListCreateAPIView):
- model = Comment
- serializer_class = CommentSerializer
+ class SnippetList(generics.ListCreateAPIView):
+ model = Snippet
+ serializer_class = SnippetSerializer
- class CommentInstance(generics.RetrieveUpdateDestroyAPIView):
- model = Comment
- serializer_class = CommentSerializer
+ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
+ model = Snippet
+ serializer_class = SnippetSerializer
Wow, that's pretty concise. We've got a huge amount for free, and our code looks like good, clean, idiomatic Django.
-Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can customize the behavior of our views to support a range of authentication, permissions, throttling and other aspects.
+Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API.
[dry]: http://en.wikipedia.org/wiki/Don't_repeat_yourself
-[tut-4]: 4-authentication-permissions-and-throttling.md
+[tut-4]: 4-authentication-and-permissions.md
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
new file mode 100644
index 00000000..79436ad4
--- /dev/null
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -0,0 +1,183 @@
+# Tutorial 4: Authentication & Permissions
+
+Currently our API doesn't have any restrictions on who can
+
+
+## Adding information to our model
+
+We're going to make a couple of changes to our `Snippet` model class.
+First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.
+
+Add the following two fields to the model.
+
+ owner = models.ForeignKey('auth.User', related_name='snippets')
+ highlighted = models.TextField()
+
+We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code higlighting library.
+
+We'll ned some extra imports:
+
+ from pygments.lexers import get_lexer_by_name
+ from pygments.formatters import HtmlFormatter
+ from pygments import highlight
+
+And now we can add a `.save()` method to our model class:
+
+ def save(self, *args, **kwargs):
+ """
+ Use the `pygments` library to create an highlighted HTML
+ representation of the code snippet.
+ """
+ lexer = get_lexer_by_name(self.language)
+ linenos = self.linenos and 'table' or False
+ options = self.title and {'title': self.title} or {}
+ formatter = HtmlFormatter(style=self.style, linenos=linenos,
+ full=True, **options)
+ self.highlighted = highlight(self.code, lexer, formatter)
+ super(Snippet, self).save(*args, **kwargs)
+
+When that's all done we'll need to update our database tables.
+Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
+
+ rm tmp.db
+ python ./manage.py syncdb
+
+You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
+
+ python ./manage.py createsuperuser
+
+## Adding endpoints for our User models
+
+Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy:
+
+ class UserSerializer(serializers.ModelSerializer):
+ snippets = serializers.ManyPrimaryKeyRelatedField()
+
+ class Meta:
+ model = User
+ fields = ('pk', 'username', 'snippets')
+
+Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we've needed to add an explicit field for it.
+
+We'll also add a couple of views. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views.
+
+ class UserList(generics.ListAPIView):
+ model = User
+ serializer_class = UserSerializer
+
+
+ class UserInstance(generics.RetrieveAPIView):
+ model = User
+ serializer_class = UserSerializer
+
+Finally we need to add those views into the API, by referencing them from the URL conf.
+
+ url(r'^users/$', views.UserList.as_view()),
+ url(r'^users/(?P[0-9]+)/$', views.UserInstance.as_view())
+
+## Associating Snippets with Users
+
+Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
+
+The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.
+
+On **both** the `SnippetList` and `SnippetInstance` view classes, add the following method:
+
+ def pre_save(self, obj):
+ obj.owner = self.request.user
+
+## Updating our serializer
+
+Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that.
+
+Add the following field to the serializer definition:
+
+ owner = serializers.Field(source='owner.username')
+
+**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
+
+This field is doing something quite interesting. The `source` argument controls which attribtue is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language.
+
+The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
+
+## Adding required permissions to views
+
+Now that code snippets are associated with users we want to make sure that only authenticated users are able to create, update and delete code snippets.
+
+REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.
+
+Add the following property to **both** the `SnippetList` and `SnippetInstance` view classes.
+
+ permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
+
+**TODO: Now that the permissions are restricted, demonstrate using HTTP basic authentication with curl requests**
+
+## Adding login to the Browseable API
+
+If you open a browser and navigate to the browseable API at the moment, you'll find you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
+
+We can add a login view for use with the browseable API, by editing our URLconf once more.
+
+Add the following import at the top of the file:
+
+ from django.conf.urls import include
+
+And, at the end of the file, add a pattern to include the login and logout views for the browseable API.
+
+ urlpatterns += patterns('',
+ url(r'^api-auth/', include('rest_framework.urls',
+ namespace='rest_framework'))
+ )
+
+The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace.
+
+Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earier, you'll be able to create code snippets again.
+
+Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet pks that are associated with each user, in each user's 'snippets' field.
+
+## Object level permissions
+
+Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able update or delete it.
+
+To do that we're going to need to create a custom permission.
+
+In the snippets app, create a new file, `permissions.py`
+
+ from rest_framework import permissions
+
+
+ class IsOwnerOrReadOnly(permissions.BasePermission):
+ """
+ Custom permission to only allow owners of an object to edit it.
+ """
+
+ def has_permission(self, request, view, obj=None):
+ # Skip the check unless this is an object-level test
+ if obj is None:
+ return True
+
+ # Read permissions are allowed to any request
+ if request.method in permissions.SAFE_METHODS:
+ return True
+
+ # Write permissions are only allowed to the owner of the snippet
+ return obj.owner == request.user
+
+Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetInstance` class:
+
+ permission_classes = (permissions.IsAuthenticatedOrReadOnly,
+ IsOwnerOrReadOnly,)
+
+Make sure to also import the `IsOwnerOrReadOnly` class.
+
+ from snippets.permissions import IsOwnerOrReadOnly
+
+Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.
+
+## Summary
+
+We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.
+
+In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
+
+[tut-5]: 5-relationships-and-hyperlinked-apis.md
\ No newline at end of file
diff --git a/docs/tutorial/4-authentication-permissions-and-throttling.md b/docs/tutorial/4-authentication-permissions-and-throttling.md
deleted file mode 100644
index c8d7cbd3..00000000
--- a/docs/tutorial/4-authentication-permissions-and-throttling.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# Tutorial 4: Authentication & Permissions
-
-Nothing to see here. Onwards to [part 5][tut-5].
-
-[tut-5]: 5-relationships-and-hyperlinked-apis.md
\ No newline at end of file
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 8600d5ed..84d02a53 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -1,11 +1,157 @@
# Tutorial 5 - Relationships & Hyperlinked APIs
-**TODO**
+At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
-* Create BlogPost model
-* Demonstrate nested relationships
-* Demonstrate and describe hyperlinked relationships
+## Creating an endpoint for the root of our API
-
+ from rest_framework import renderers
+ from rest_framework.decorators import api_view
+ from rest_framework.response import Response
+ from rest_framework.reverse import reverse
+
+
+ @api_view(('GET',))
+ def api_root(request, format=None):
+ return Response({
+ 'users': reverse('user-list', request=request),
+ 'snippets': reverse('snippet-list', request=request)
+ })
+
+Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs.
+
+## Creating an endpoint for the highlighted snippets
+
+The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
+
+Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two style of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
+
+The other thing we need to consider when creating the code highlight view is that there's no existing concreate generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
+
+Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method.
+
+ class SnippetHighlight(generics.SingleObjectAPIView):
+ model = Snippet
+ renderer_classes = (renderers.StaticHTMLRenderer,)
+
+ def get(self, request, *args, **kwargs):
+ snippet = self.get_object()
+ return Response(snippet.highlighted)
+
+As usual we need to add the new views that we've created in to our URLconf.
+We'll add a url pattern for our new API root:
+
+ url(r'^$', 'api_root'),
+
+And then add a url pattern for the snippet highlights:
+
+ url(r'^snippets/(?P[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
+
+## Hyperlinking our API
+
+Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
+
+* Using primary keys.
+* Using hyperlinking between entities.
+* Using a unique identifying slug field on the related entity.
+* Using the default string representation of the related entity.
+* Nesting the related entity inside the parent representation.
+* Some other custom representation.
+
+REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
+
+In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer` instead of the existing `ModelSerializer`.
+
+The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`:
+
+* It does not include the `pk` field by default.
+* It includes a `url` field, using `HyperlinkedIdentityField`.
+* Relationships use `HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField`,
+ instead of `PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField`.
+
+We can easily re-write our existing serializers to use hyperlinking.
+
+ class SnippetSerializer(serializers.HyperlinkedModelSerializer):
+ owner = serializers.Field(source='owner.username')
+ highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight')
+
+ class Meta:
+ model = models.Snippet
+ fields = ('url', 'highlight', 'owner',
+ 'title', 'code', 'linenos', 'language', 'style')
+
+
+ class UserSerializer(serializers.HyperlinkedModelSerializer):
+ snippets = serializers.ManyHyperlinkedRelatedField(view_name='snippet-detail')
+
+ class Meta:
+ model = User
+ fields = ('url', 'username', 'snippets')
+
+Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
+
+## Making sure our URL patterns are named
+
+If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
+
+* The root of our API refers to `'user-list'` and `'snippet-list'`.
+* Our snippet serializer includes a field that refers to `'snippet-highlight'`.
+* Our user serializer includes a field that refers to `'snippet-detail'`.
+* Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`.
+
+After adding all those names into our URLconf, our final `'urls.py'` file should look something like this:
+
+ # API endpoints
+ urlpatterns = format_suffix_patterns(patterns('snippets.views',
+ url(r'^$', 'api_root'),
+ url(r'^snippets/$',
+ views.SnippetList.as_view(),
+ name='snippet-list'),
+ url(r'^snippets/(?P[0-9]+)/$',
+ views.SnippetInstance.as_view(),
+ name='snippet-detail'),
+ url(r'^snippets/(?P[0-9]+)/highlight/$'
+ views.SnippetHighlight.as_view(),
+ name='snippet-highlight'),
+ url(r'^users/$',
+ views.UserList.as_view(),
+ name='user-list'),
+ url(r'^users/(?P[0-9]+)/$',
+ views.UserInstance.as_view(),
+ name='user-detail')
+ ))
+
+ # Login and logout views for the browsable API
+ urlpatterns += patterns('',
+ url(r'^api-auth/', include('rest_framework.urls',
+ namespace='rest_framework'))
+ )
+
+## Reviewing our work
+
+If we open a browser and navigate to the browseable API, you'll find that you can now work your way around the API simply by following links.
+
+You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the hightlighted code HTML representations.
+
+We've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
+
+We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
+
+You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
+
+## Onwards and upwards.
+
+We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
+
+* Contribute on [GitHub][github] by reviewing and subitting issues, and making pull requests.
+* Join the [REST framework discussion group][group], and help build the community.
+* Follow the author [on Twitter][twitter] and say hi.
+
+**Now go build some awesome things.**
+
+[repo]: https://github.com/tomchristie/rest-framework-tutorial
+[sandbox]: http://sultry-coast-6726.herokuapp.com/
+[github]: https://github.com/tomchristie/django-rest-framework
+[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
+[twitter]: https://twitter.com/_tomchristie
\ No newline at end of file
--
cgit v1.2.3
From db635fa6327d8d3ac3b06886c5f459b5c5a5cd04 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 19:37:27 +0000
Subject: Minor fixes
---
docs/index.md | 6 ++----
docs/template.html | 3 +--
docs/tutorial/1-serialization.md | 6 +++---
docs/tutorial/2-requests-and-responses.md | 8 ++++----
docs/tutorial/4-authentication-and-permissions.md | 2 ++
5 files changed, 12 insertions(+), 13 deletions(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index f66ba7f4..bd0c007d 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -67,9 +67,8 @@ The tutorial will walk you through the building blocks that make up REST framewo
* [1 - Serialization][tut-1]
* [2 - Requests & Responses][tut-2]
* [3 - Class based views][tut-3]
-* [4 - Authentication, permissions & throttling][tut-4]
+* [4 - Authentication & permissions][tut-4]
* [5 - Relationships & hyperlinked APIs][tut-5]
-
## API Guide
@@ -161,9 +160,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[tut-1]: tutorial/1-serialization.md
[tut-2]: tutorial/2-requests-and-responses.md
[tut-3]: tutorial/3-class-based-views.md
-[tut-4]: tutorial/4-authentication-permissions-and-throttling.md
+[tut-4]: tutorial/4-authentication-and-permissions.md
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
-[tut-6]: tutorial/6-resource-orientated-projects.md
[request]: api-guide/requests.md
[response]: api-guide/responses.md
diff --git a/docs/template.html b/docs/template.html
index 56c5d832..557b45b3 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -57,9 +57,8 @@
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index fc052202..c1ab49d1 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -278,13 +278,13 @@ We'll also need a view which corresponds to an individual snippet, and can be us
snippet.delete()
return HttpResponse(status=204)
-Finally we need to wire these views up. Create the `snippet/urls.py` file:
+Finally we need to wire these views up. Create the `snippets/urls.py` file:
from django.conf.urls import patterns, url
urlpatterns = patterns('snippets.views',
- url(r'^snippet/$', 'snippet_list'),
- url(r'^snippet/(?P[0-9]+)/$', 'snippet_detail')
+ url(r'^snippets/$', 'snippet_list'),
+ url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail')
)
It's worth noting that there's a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index 76803d24..938739fa 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -114,8 +114,8 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = patterns('snippet.views',
- url(r'^$', 'snippet_list'),
- url(r'^(?P[0-9]+)$', 'snippet_detail')
+ url(r'^snippets/$', 'snippet_list'),
+ url(r'^snippets/(?P[0-9]+)$', 'snippet_detail')
)
urlpatterns = format_suffix_patterns(urlpatterns)
@@ -128,7 +128,7 @@ Go ahead and test the API from the command line, as we did in [tutorial part 1][
**TODO: Describe using accept headers, content-type headers, and format suffixed URLs**
-Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/][devserver]."
+Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/snippets/][devserver]."
**Note: Right now the Browseable API only works with the CBV's. Need to fix that.**
@@ -144,7 +144,7 @@ See the [browsable api][browseable-api] topic for more information about the bro
In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write.
[json-url]: http://example.com/api/items/4.json
-[devserver]: http://127.0.0.1:8000/
+[devserver]: http://127.0.0.1:8000/snippets/
[browseable-api]: ../topics/browsable-api.md
[tut-1]: 1-serialization.md
[tut-3]: 3-class-based-views.md
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 79436ad4..336d5891 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -100,6 +100,8 @@ This field is doing something quite interesting. The `source` argument controls
The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
+**TODO: Explain the SessionAuthentication and BasicAuthentication classes, and demonstrate using HTTP basic authentication with curl requests**
+
## Adding required permissions to views
Now that code snippets are associated with users we want to make sure that only authenticated users are able to create, update and delete code snippets.
--
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')
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')
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')
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 f2d63467764fd3784e9eb207bdb5b5387e7cd516 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 20:50:37 +0000
Subject: Add initial explanatory paragraph
---
docs/tutorial/4-authentication-and-permissions.md | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 336d5891..a0d7c5a6 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -1,7 +1,11 @@
# Tutorial 4: Authentication & Permissions
-Currently our API doesn't have any restrictions on who can
+Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:
+* Code snippets are always associated with a creator.
+* Only authenticated users may create snippets.
+* Only the creator of a snippet may update or delete it.
+* Unauthenticated requests should have full read-only access.
## Adding information to our model
--
cgit v1.2.3
From bdd939f1f3ac726bfe293e956995da57eced4640 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 20:50:51 +0000
Subject: Remove unfinished sections from the index
---
docs/index.md | 2 --
docs/template.html | 2 --
2 files changed, 4 deletions(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index 6115d17d..b6eebc5f 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -97,11 +97,9 @@ The API guide is your complete reference manual to all the functionality provide
General guides to using REST framework.
-* [CSRF][csrf]
* [Browser enhancements][browser-enhancements]
* [The Browsable API][browsableapi]
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
-* [Contributing to REST framework][contributing]
* [2.0 Announcement][rest-framework-2-announcement]
* [Release Notes][release-notes]
* [Credits][credits]
diff --git a/docs/template.html b/docs/template.html
index f0f6afe7..fcceede5 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -87,11 +87,9 @@
--
cgit v1.2.3
From 411c95ea0e1051aca78e4fb02152a983bea830cc Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 20:54:12 +0000
Subject: Tweaks
---
docs/index.md | 1 -
docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +-
2 files changed, 1 insertion(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index b6eebc5f..4126fc77 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -116,7 +116,6 @@ Run the tests:
./rest_framework/runtests/runtests.py
-For more information see the [Contributing to REST framework][contributing] section.
## Support
For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`.
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 84d02a53..38e32157 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -140,7 +140,7 @@ We've walked through each step of the design process, and seen how if we need to
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
-## Onwards and upwards.
+## Onwards and upwards
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
--
cgit v1.2.3
From 0c71b4c10095f8783f205fc134a475c04a27f01b Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Sun, 28 Oct 2012 21:16:04 +0000
Subject: Tweaks
---
docs/topics/rest-framework-2-announcement.md | 22 +++++++++++-----------
1 file changed, 11 insertions(+), 11 deletions(-)
(limited to 'docs')
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index 98e66228..82e8fe36 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -56,16 +56,6 @@ REST framework 2 also allows you to work with both function-based and class-base
Pretty much every aspect of REST framework has been reworked, with the aim of ironing out some of the design flaws of the previous versions. Each of the components of REST framework are cleanly decoupled, and can be used independantly of each-other, and there are no monolithic resource classes, overcomplicated mixin combinations, or opinionated serialization or URL routing decisions.
-## Documentation
-
-As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
-
-In the author's opinion, using `markdown` for documentation is a much better option that `rst`. It is intuitive and readable, and there is great tooling available, such as the [Mou][mou] editor for Mac OS X, which makes it easy and plesant to work.
-
-We're really pleased with how the docs style looks - it's simple and clean, and the docs build much more quickly than with the previous sphinx setup. We'll miss being able to use the wonderful [Read the Docs][readthedocs] service, but we think it's a trade-off worth making.
-
-Developing REST framework's documentation builder into a fully-fledged reusable project is something that we have planned for a future date.
-
## The Browseable API
Django REST framework's most unique feature is the way it is able to serve up both machine-readable representations, and a fully browsable HTML representation to the same endpoints.
@@ -76,6 +66,16 @@ With REST framework 2, the browseable API gets a snazzy new bootstrap-based them
There are also some functionality improvments - actions such as as `POST` and `DELETE` will only display if the user has the appropriate permissions.
+![Browseable API][image]
+
+**Image above**: An example of the browseable API in REST framework 2
+
+## Documentation
+
+As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
+
+We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great. We'll miss being able to use the wonderful [Read the Docs][readthedocs] service, but we think it's a trade-off worth making.
+
## Summary
In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
@@ -84,5 +84,5 @@ In short, we've engineered the hell outta this thing, and we're incredibly proud
[quote1]: https://twitter.com/kobutsu/status/261689665952833536
[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J
[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ
-[mou]: http://mouapp.com/
+[image]: ../img/quickstart.png
[readthedocs]: https://readthedocs.org/
--
cgit v1.2.3
From 76db7d4c590957c7e81ce521a1ab5bfb6760afaf Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 08:54:14 +0100
Subject: correct code indent
---
docs/tutorial/1-serialization.md | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
(limited to 'docs')
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index c1ab49d1..f6dcca13 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -87,8 +87,8 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
- default='friendly',
- max_length=100)
+ default='friendly',
+ max_length=100)
class Meta:
ordering = ('created',)
--
cgit v1.2.3
From c6240f4514ad34c53122eed77a349b71f28d8847 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Mon, 29 Oct 2012 08:58:29 +0100
Subject: removed empty row
---
docs/tutorial/1-serialization.md | 1 -
1 file changed, 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index f6dcca13..7330fdef 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -219,7 +219,6 @@ Edit the `snippet/views.py` file, and add the following.
"""
An HttpResponse that renders it's content into JSON.
"""
-
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
--
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')
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')
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')
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')
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')
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')
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')
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')
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')
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')
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 076ca51d6f1e8e22c74810bfcfef76e108cbce77 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 29 Oct 2012 08:53:12 +0000
Subject: Added @minddust. Thanks!
---
docs/topics/credits.md | 2 ++
1 file changed, 2 insertions(+)
(limited to 'docs')
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index a317afde..3b430e42 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -50,6 +50,7 @@ The following people have helped make REST framework great.
* Rob Dobson - [rdobson]
* Daniel Vaca Araujo - [diviei]
* Madis Väin - [madisvain]
+* Stephan Groß - [minddust]
Many thanks to everyone who's contributed to the project.
@@ -131,3 +132,4 @@ To contact the author directly:
[rdobson]: https://github.com/rdobson
[diviei]: https://github.com/diviei
[madisvain]: https://github.com/madisvain
+[minddust]: https://github.com/minddust
\ No newline at end of file
--
cgit v1.2.3
From cf77fd6964c9f226a7c3f6dc5ec9d74a76cc1ab6 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Mon, 29 Oct 2012 09:10:04 +0000
Subject: Tweak
---
docs/topics/rest-framework-2-announcement.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index 82e8fe36..7b97af73 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -74,7 +74,7 @@ There are also some functionality improvments - actions such as as `POST` and `D
As you can see the documentation for REST framework has been radically improved. It gets a completely new style, using markdown for the documentation source, and a bootstrap-based theme for the styling.
-We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great. We'll miss being able to use the wonderful [Read the Docs][readthedocs] service, but we think it's a trade-off worth making.
+We're really pleased with how the docs style looks - it's simple and clean, is easy to navigate around, and we think it reads great.
## Summary
--
cgit v1.2.3
From 5f0d4ef2fcbb0206ae456dd6553551cd0039c92d Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 30 Oct 2012 10:30:41 +0000
Subject: Update browser enhancments docs. Fixes #339.
---
docs/topics/browser-enhancements.md | 49 ++++++++++++++++++++++++++-----------
1 file changed, 35 insertions(+), 14 deletions(-)
(limited to 'docs')
diff --git a/docs/topics/browser-enhancements.md b/docs/topics/browser-enhancements.md
index d4e128ae..6a11f0fa 100644
--- a/docs/topics/browser-enhancements.md
+++ b/docs/topics/browser-enhancements.md
@@ -2,42 +2,63 @@
> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE"
>
-> — [RESTful Web Services](1), Leonard Richardson & Sam Ruby.
+> — [RESTful Web Services][cite], Leonard Richardson & Sam Ruby.
## Browser based PUT, DELETE, etc...
-**TODO: Preamble.** Note that this is the same strategy as is used in [Ruby on Rails](2).
+REST framework supports browser-based `PUT`, `DELETE` and other methods, by
+overloading `POST` requests using a hidden form field.
+
+Note that this is the same strategy as is used in [Ruby on Rails][rails].
For example, given the following form:
+
+
`request.method` would return `"DELETE"`.
## Browser based submission of non-form content
-Browser-based submission of content types other than form are supported by using form fields named `_content` and `_content_type`:
+Browser-based submission of content types other than form are supported by
+using form fields named `_content` and `_content_type`:
For example, given the following form:
+
+
+
-`request.content_type` would return `"application/json"`, and `request.stream` would return `"{'count': 1}"`
+`request.content_type` would return `"application/json"`, and
+`request.stream` would return `"{'count': 1}"`
## URL based accept headers
+REST framework can take `?accept=application/json` style URL parameters,
+which allow the `Accept` header to be overridden.
+
+This can be useful for testing the API from a web browser, where you don't
+have any control over what is sent in the `Accept` header.
+
## URL based format suffixes
+REST framework can take `?format=json` style URL parameters, which can be a
+useful shortcut for determing which content type should be returned from
+the view.
+
+This is a more concise than using the `accept` override, but it also gives
+you less control. (For example you can't specify any media type parameters)
+
## Doesn't HTML5 support PUT and DELETE forms?
-Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec](3). There remains [ongoing discussion](4) about adding support for `PUT` and `DELETE`, as well as how to support content types other than form-encoded data.
+Nope. It was at one point intended to support `PUT` and `DELETE` forms, but
+was later [dropped from the spec][html5]. There remains
+[ongoing discussion][put_delete] about adding support for `PUT` and `DELETE`,
+as well as how to support content types other than form-encoded data.
-[1]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
-[2]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
-[3]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
-[4]: http://amundsen.com/examples/put-delete-forms/
+[cite]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
+[rails]: http://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work
+[html5]: http://www.w3.org/TR/html5-diff/#changes-2010-06-24
+[put_delete]: http://amundsen.com/examples/put-delete-forms/
--
cgit v1.2.3
From 29bc52096a40c3f483e763cf562815ded3e56faa Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 30 Oct 2012 11:55:02 +0000
Subject: Docs tweaks for tutorial.
---
docs/tutorial/5-relationships-and-hyperlinked-apis.md | 18 +++++++++++++++++-
1 file changed, 17 insertions(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 38e32157..777aa5e1 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -74,7 +74,7 @@ We can easily re-write our existing serializers to use hyperlinking.
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
- highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight')
+ highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
class Meta:
model = models.Snippet
@@ -91,6 +91,8 @@ We can easily re-write our existing serializers to use hyperlinking.
Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern.
+Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix.
+
## Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
@@ -128,6 +130,20 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
namespace='rest_framework'))
)
+## Adding pagination
+
+The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
+
+We can change the default list style to use pagination, by modifying our `settings.py` file slightly. Add the following setting:
+
+ REST_FRAMEWORK = {
+ 'PAGINATE_BY': 10
+ }
+
+Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well seperated from your other project settings.
+
+We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
+
## Reviewing our work
If we open a browser and navigate to the browseable API, you'll find that you can now work your way around the API simply by following links.
--
cgit v1.2.3
From 41ab18b13ec6d96906463a3b05680226c7245b6d Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 30 Oct 2012 12:23:17 +0000
Subject: Docs update
---
docs/index.md | 19 ++++++++++++++++---
docs/topics/rest-framework-2-announcement.md | 8 +++++++-
docs/tutorial/1-serialization.md | 8 ++++++++
docs/tutorial/5-relationships-and-hyperlinked-apis.md | 2 +-
4 files changed, 32 insertions(+), 5 deletions(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index 4126fc77..5b6fcd9c 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -5,12 +5,24 @@
**A toolkit for building well-connected, self-describing Web APIs.**
-**WARNING: This documentation is for the 2.0 redesign of REST framework. It is a work in progress.**
+---
+
+**Note**: This documentation is for the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub.
+
+---
Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box.
+If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities.
+
+There is also a sandbox API you can use for testing purposes, [available here][sandbox].
+
+**Below**: *Screenshot from the browseable API*
+
+![Screenshot][image]
+
## Requirements
REST framework requires the following:
@@ -25,8 +37,6 @@ The following packages are optional:
## Installation
-**WARNING: These instructions will only become valid once this becomes the master version**
-
Install using `pip`, including any optional packages you want...
pip install djangorestframework
@@ -152,6 +162,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML
+[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
+[image]: img/quickstart.png
+[sandbox]: http://restframework.herokuapp.com/
[quickstart]: tutorial/quickstart.md
[tut-1]: tutorial/1-serialization.md
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index 7b97af73..e77575b2 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -6,7 +6,13 @@ What it is, and why you should care
>
> — [Roy Fielding][cite]
-REST framework 2 is an almost complete reworking of the original framework, which comprehensivly addresses some of the original design issues.
+---
+
+**Announcement:** REST framework 2 released - Tue 30th Oct 2012
+
+---
+
+REST framework 2 is an almost complete reworking of the original framework, which comprehensively addresses some of the original design issues.
Because the latest version should be considered a re-release, rather than an incremental improvement, we've skipped a version, and called this release Django REST framework 2.0.
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index 7330fdef..19fc28a5 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -6,6 +6,12 @@ This tutorial will cover creating a simple pastebin code highlighting Web API. A
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
+---
+
+**Note**: The final code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. There is also a sandbox version for testing, [available here][sandbox].
+
+---
+
## Setting up a new environment
Before we do anything else we'll create a new virtual environment, using [virtualenv]. This will make sure our package configuration is keep nicely isolated from any other projects we're working on.
@@ -303,5 +309,7 @@ Our API views don't do anything particularly special at the moment, beyond serve
We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
[quickstart]: quickstart.md
+[repo]: https://github.com/tomchristie/rest-framework-tutorial
+[sandbox]: http://restframework.herokuapp.com/
[virtualenv]: http://www.virtualenv.org/en/latest/index.html
[tut-2]: 2-requests-and-responses.md
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 777aa5e1..1f663745 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -167,7 +167,7 @@ We've reached the end of our tutorial. If you want to get more involved in the
**Now go build some awesome things.**
[repo]: https://github.com/tomchristie/rest-framework-tutorial
-[sandbox]: http://sultry-coast-6726.herokuapp.com/
+[sandbox]: http://restframework.herokuapp.com/
[github]: https://github.com/tomchristie/django-rest-framework
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[twitter]: https://twitter.com/_tomchristie
\ No newline at end of file
--
cgit v1.2.3
From 9aa37260098b5ec2750090fb035945780b35ad1d Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 30 Oct 2012 13:50:07 +0100
Subject: fix ModelSerializer useage
cause of:
from snippets.models import Snippet
---
docs/tutorial/1-serialization.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index 7330fdef..0b84a779 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -194,7 +194,7 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
- model = models.Snippet
+ model = Snippet
fields = ('pk', 'title', 'code', 'linenos', 'language', 'style')
--
cgit v1.2.3
From bcfb46eedc8fd7184e73a1fa6cecb1a359d1ef1f Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 30 Oct 2012 14:02:12 +0100
Subject: removed empty row
---
docs/tutorial/3-class-based-views.md | 1 -
1 file changed, 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index 3d58fe8e..f27b5af0 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -36,7 +36,6 @@ So far, so good. It looks pretty similar to the previous case, but we've got be
"""
Retrieve, update or delete a snippet instance.
"""
-
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
--
cgit v1.2.3
From abf7f1161933567e622c51af9a53e4b860c11693 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 30 Oct 2012 14:11:36 +0100
Subject: fixed typo
---
docs/tutorial/4-authentication-and-permissions.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index a0d7c5a6..2dc62219 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -19,7 +19,7 @@ Add the following two fields to the model.
We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code higlighting library.
-We'll ned some extra imports:
+We'll need some extra imports:
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
--
cgit v1.2.3
From a967187b4102af88dec4d8a2b9ffd97b6c65db0b Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 30 Oct 2012 14:36:37 +0100
Subject: fixed typo
---
docs/tutorial/4-authentication-and-permissions.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 2dc62219..5a30082c 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -100,7 +100,7 @@ Add the following field to the serializer definition:
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
-This field is doing something quite interesting. The `source` argument controls which attribtue is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language.
+This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language.
The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
--
cgit v1.2.3
From aa081678d5fecf6a17b411545571348e047c6846 Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 30 Oct 2012 14:38:23 +0100
Subject: added missing word
---
docs/tutorial/4-authentication-and-permissions.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 5a30082c..ca6ab80c 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -100,7 +100,7 @@ Add the following field to the serializer definition:
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
-This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as is used with Django's template language.
+This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
--
cgit v1.2.3
From 3216ac022419710485695a9a21f083f08e012a7f Mon Sep 17 00:00:00 2001
From: Stephan Groß
Date: Tue, 30 Oct 2012 14:53:38 +0100
Subject: added missing word + removed double whitespace
---
docs/tutorial/4-authentication-and-permissions.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index ca6ab80c..b0ed8f2a 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -120,7 +120,7 @@ Add the following property to **both** the `SnippetList` and `SnippetInstance` v
## Adding login to the Browseable API
-If you open a browser and navigate to the browseable API at the moment, you'll find you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
+If you open a browser and navigate to the browseable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
We can add a login view for use with the browseable API, by editing our URLconf once more.
--
cgit v1.2.3
From 4cdd0b845e10c433358f210c84a2b3fe28543c68 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 30 Oct 2012 13:59:31 +0000
Subject: Final docs tweaks for 2.0
---
docs/index.md | 2 ++
docs/template.html | 2 +-
docs/topics/credits.md | 4 ++++
docs/topics/rest-framework-2-announcement.md | 8 +++++++-
docs/tutorial/1-serialization.md | 2 +-
5 files changed, 15 insertions(+), 3 deletions(-)
(limited to 'docs')
diff --git a/docs/index.md b/docs/index.md
index 5b6fcd9c..a96d0925 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -66,9 +66,11 @@ If you're intending to use the browseable API you'll want to add REST framework'
Note that the URL path can be whatever you want, but you must include `rest_framework.urls` with the `rest_framework` namespace.
+
## Tutorial
diff --git a/docs/template.html b/docs/template.html
index fcceede5..08387968 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -53,7 +53,7 @@
diff --git a/docs/topics/credits.md b/docs/topics/credits.md
index 3b430e42..69d57802 100644
--- a/docs/topics/credits.md
+++ b/docs/topics/credits.md
@@ -62,6 +62,8 @@ Project hosting is with [GitHub].
Continuous integration testing is managed with [Travis CI][travis-ci].
+The [live sandbox][sandbox] is hosted on [Heroku].
+
Various inspiration taken from the [Piston], [Tastypie] and [Dagny] projects.
Development of REST framework 2.0 was sponsored by [DabApps].
@@ -83,6 +85,8 @@ To contact the author directly:
[tastypie]: https://github.com/toastdriven/django-tastypie
[dagny]: https://github.com/zacharyvoase/dagny
[dabapps]: http://lab.dabapps.com
+[sandbox]: http://restframework.herokuapp.com/
+[heroku]: http://www.heroku.com/
[tomchristie]: https://github.com/tomchristie
[markotibold]: https://github.com/markotibold
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index e77575b2..885d1918 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -1,6 +1,6 @@
# Django REST framework 2
-What it is, and why you should care
+What it is, and why you should care.
> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
>
@@ -86,9 +86,15 @@ We're really pleased with how the docs style looks - it's simple and clean, is e
In short, we've engineered the hell outta this thing, and we're incredibly proud of the result.
+If you're interested please take a browse around the documentation. [The tutorial][tut] is a great place to get started.
+
+There's also a [live sandbox version of the tutorial API][sandbox] available for testing.
+
[cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven#comment-724
[quote1]: https://twitter.com/kobutsu/status/261689665952833536
[quote2]: https://groups.google.com/d/msg/django-rest-framework/heRGHzG6BWQ/ooVURgpwVC0J
[quote3]: https://groups.google.com/d/msg/django-rest-framework/flsXbvYqRoY/9lSyntOf5cUJ
[image]: ../img/quickstart.png
[readthedocs]: https://readthedocs.org/
+[tut]: ../tutorial/1-serialization.md
+[sandbox]: http://restframework.herokuapp.com/
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index 19fc28a5..77a7641f 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -4,7 +4,7 @@
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
-The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
+The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started.
---
--
cgit v1.2.3
From 4e7805cb24d73e7f706318b5e5a27e3f9ba39d14 Mon Sep 17 00:00:00 2001
From: Tom Christie
Date: Tue, 30 Oct 2012 14:18:16 +0000
Subject: Make docs ready to push to django-rest-framework.org
---
docs/template.html | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'docs')
diff --git a/docs/template.html b/docs/template.html
index 08387968..94fc269f 100644
--- a/docs/template.html
+++ b/docs/template.html
@@ -40,7 +40,7 @@