Skip to content

Commit 90247af

Browse files
committed
Docs on Forms API
1 parent 41182c6 commit 90247af

File tree

9 files changed

+228
-6
lines changed

9 files changed

+228
-6
lines changed

docs/api-guide/fields.md

+4-3
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,9 @@ A value that should be used for pre-populating the value of HTML form fields.
8585

8686
### `style`
8787

88-
A dictionary of key-value pairs that can be used to control how renderers should render the field. The API for this should still be considered experimental, and will be formalized with the 3.1 release.
88+
A dictionary of key-value pairs that can be used to control how renderers should render the field.
8989

90-
Two options are currently used in HTML form generation, `'input_type'` and `'base_template'`.
90+
Two examples here are `'input_type'` and `'base_template'`:
9191

9292
# Use <input type="password"> for the input.
9393
password = serializers.CharField(
@@ -100,7 +100,7 @@ Two options are currently used in HTML form generation, `'input_type'` and `'bas
100100
style = {'base_template': 'radio.html'}
101101
}
102102

103-
**Note**: The `style` argument replaces the old-style version 2.x `widget` keyword argument. Because REST framework 3 now uses templated HTML form generation, the `widget` option that was used to support Django built-in widgets can no longer be supported. Version 3.3 is planned to include public API support for customizing HTML form generation.
103+
For more details see the [HTML & Forms][html-and-forms] documentation.
104104

105105
---
106106

@@ -658,6 +658,7 @@ The [django-rest-framework-gis][django-rest-framework-gis] package provides geog
658658
The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreField` to support [django-hstore][django-hstore] `DictionaryField` model field.
659659

660660
[cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data
661+
[html-and-forms]: ../topics/html-and-forms.md
661662
[FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS
662663
[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
663664
[strftime]: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

docs/api-guide/renderers.md

+3
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,8 @@ This renderer is not intended to be used directly, but can instead be used in te
209209
<input type="submit" value="Save" />
210210
</form>
211211

212+
For more information see the [HTML & Forms][html-and-forms] documentation.
213+
212214
**.media_type**: `text/html`
213215

214216
**.format**: `'.form'`
@@ -463,6 +465,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
463465

464466
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
465467
[conneg]: content-negotiation.md
468+
[html-and-forms]: ../topics/html-and-forms.md
466469
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
467470
[testing]: testing.md
468471
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas

docs/img/horizontal.png

11.4 KB
Loading

docs/img/inline.png

8.1 KB
Loading

docs/img/vertical.png

11.7 KB
Loading

docs/index.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,9 @@ The API guide is your complete reference manual to all the functionality provide
191191
General guides to using REST framework.
192192

193193
* [Documenting your API][documenting-your-api]
194+
* [Internationalization][internationalization]
194195
* [AJAX, CSRF & CORS][ajax-csrf-cors]
196+
* [HTML & Forms][html-and-forms]
195197
* [Browser enhancements][browser-enhancements]
196198
* [The Browsable API][browsableapi]
197199
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
@@ -303,8 +305,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
303305
[settings]: api-guide/settings.md
304306

305307
[documenting-your-api]: topics/documenting-your-api.md
306-
[internationalization]: topics/documenting-your-api.md
308+
[internationalization]: topics/internationalization.md
307309
[ajax-csrf-cors]: topics/ajax-csrf-cors.md
310+
[html-and-forms]: topics/html-and-forms.md
308311
[browser-enhancements]: topics/browser-enhancements.md
309312
[browsableapi]: topics/browsable-api.md
310313
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md

docs/topics/html-and-forms.md

+214
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
# HTML & Forms
2+
3+
REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates.
4+
5+
## Rendering HTML
6+
7+
In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`.
8+
9+
The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response.
10+
11+
The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content.
12+
13+
Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views.
14+
15+
Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template:
16+
17+
**views.py**:
18+
19+
from my_project.example.models import Profile
20+
from rest_framework.renderers import TemplateHTMLRenderer
21+
from rest_framework.views import APIView
22+
23+
24+
class ProfileList(APIView):
25+
renderer_classes = [TemplateHTMLRenderer]
26+
template_name = 'profile_list.html'
27+
28+
def get(self, request):
29+
queryset = Profile.objects.all()
30+
return Response({'profiles': queryset})
31+
32+
**profile_list.html**:
33+
34+
<html><body>
35+
<h1>Profiles</h1>
36+
<ul>
37+
{% for profile in profiles %}
38+
<li>{{ profile.name }}</li>
39+
{% endfor %}
40+
</ul>
41+
</body></html>
42+
43+
## Rendering Forms
44+
45+
Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template.
46+
47+
The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance:
48+
49+
**views.py**:
50+
51+
from django.shortcuts import get_object_or_404
52+
from my_project.example.models import Profile
53+
from rest_framework.renderers import TemplateHTMLRenderer
54+
from rest_framework.views import APIView
55+
56+
57+
class ProfileDetail(APIView):
58+
renderer_classes = [TemplateHTMLRenderer]
59+
template_name = 'profile_detail.html'
60+
61+
def get(self, request, pk):
62+
profile = get_object_or_404(Profile, pk=pk)
63+
serializer = ProfileSerializer(profile)
64+
return Response({'serializer': serializer, 'profile': profile})
65+
66+
def post(self, request, pk):
67+
profile = get_object_or_404(Profile, pk=pk)
68+
serializer = ProfileSerializer(profile)
69+
if not serializer.is_valid():
70+
return Response({'serializer': serializer, 'profile': profile}) return redirect('profile-list')
71+
72+
**profile_detail.html**:
73+
74+
{% load rest_framework %}
75+
76+
<html><body>
77+
78+
<h1>Profile - {{ profile.name }}</h1>
79+
80+
<form action="{% url 'profile-detail' pk=profile.pk '%}" method="POST">
81+
{% csrf_token %}
82+
{% render_form serializer %}
83+
<input type="submit" value="Save">
84+
</form>
85+
86+
</body></html>
87+
88+
### Using template packs
89+
90+
The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields.
91+
92+
REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS.
93+
94+
The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS:
95+
96+
<head>
97+
98+
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
99+
</head>
100+
101+
Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates.
102+
103+
Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form.
104+
105+
class LoginSerializer(serializers.Serializer):
106+
email = serializers.EmailField(
107+
max_length=100,
108+
style={'placeholder': 'Email'}
109+
)
110+
password = serializers.CharField(
111+
max_length=100,
112+
style={'input_type': 'password', 'placeholder': 'Password'}
113+
)
114+
remember_me = serializers.BooleanField()---
115+
116+
#### `rest_framework/vertical`
117+
118+
Presents form labels above their corresponding control inputs, using the standard Bootstrap layout.
119+
120+
*This is the default template pack.*
121+
122+
{% load rest_framework %}
123+
124+
...
125+
126+
<form action="{% url 'login' %}" method="post" novalidate>
127+
{% csrf_token %}
128+
{% render_form serializer template_pack='rest_framework/vertical' %}
129+
<button type="submit" class="btn btn-default">Sign in</button>
130+
</form>
131+
132+
![Vertical form example](../img/vertical.png)
133+
134+
---
135+
#### `rest_framework/horizontal`
136+
137+
Presents labels and controls alongside each other, using a 2/10 column split.
138+
139+
*This is the form style used in the browsable API and admin renderers.*
140+
141+
{% load rest_framework %}
142+
143+
...
144+
145+
<form class="form-horizontal" action="{% url 'login' %}" method="post" novalidate>
146+
{% csrf_token %}
147+
{% render_form serializer %}
148+
<div class="form-group">
149+
<div class="col-sm-offset-2 col-sm-10">
150+
<button type="submit" class="btn btn-default">Sign in</button>
151+
</div>
152+
</div>
153+
</form>
154+
155+
![Horizontal form example](../img/horizontal.png)
156+
157+
---
158+
159+
#### `rest_framework/inline`
160+
161+
A compact form style that presents all the controls inline.
162+
163+
{% load rest_framework %}
164+
165+
...
166+
167+
<form class="form-inline" action="{% url 'login' %}" method="post" novalidate>
168+
{% csrf_token %}
169+
{% render_form serializer template_pack='rest_framework/inline' %}
170+
<button type="submit" class="btn btn-default">Sign in</button>
171+
</form>
172+
173+
![Inline form example](../img/inline.png)
174+
175+
## Field styles
176+
177+
Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used.
178+
179+
The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use.
180+
181+
For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this:
182+
183+
details = serializers.CharField(
184+
max_length=1000,
185+
style={'base_template': 'textarea.html'}
186+
)
187+
188+
If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name:
189+
190+
details = serializers.CharField(
191+
max_length=1000,
192+
style={'template': 'my-field-templates/custom-input.html'}
193+
)
194+
195+
Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control.
196+
197+
details = serializers.CharField(
198+
max_length=1000,
199+
style={'base_template': 'textarea.html', 'rows': 10}
200+
)
201+
202+
The complete list of `base_template` options and their associated style options is listed below.
203+
204+
base_template | Valid field types | Additional style options
205+
----|----|----
206+
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label
207+
textarea.html | `CharField` | rows, placeholder, hide_label
208+
select.html | `ChoiceField` or relational field types | hide_label
209+
radio.html | `ChoiceField` or relational field types | inline, hide_label
210+
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
211+
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
212+
checkbox.html | `BooleanField` | hide_label
213+
fieldset.html | Nested serializer | hide_label
214+
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label

mkdocs.yml

+1
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ pages:
4747
- 'Documenting your API': 'topics/documenting-your-api.md'
4848
- 'Internationalization': 'topics/internationalization.md'
4949
- 'AJAX, CSRF & CORS': 'topics/ajax-csrf-cors.md'
50+
- 'HTML & Forms': 'topics/html-and-forms.md'
5051
- 'Browser Enhancements': 'topics/browser-enhancements.md'
5152
- 'The Browsable API': 'topics/browsable-api.md'
5253
- 'REST, Hypermedia & HATEOAS': 'topics/rest-hypermedia-hateoas.md'

rest_framework/renderers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ class HTMLFormRenderer(BaseRenderer):
249249
media_type = 'text/html'
250250
format = 'form'
251251
charset = 'utf-8'
252-
template_pack = 'rest_framework/horizontal/'
252+
template_pack = 'rest_framework/vertical/'
253253
base_template = 'form.html'
254254

255255
default_style = ClassLookupDict({
@@ -495,7 +495,7 @@ def get_rendered_html_form(self, data, view, method, request):
495495
return form_renderer.render(
496496
serializer.data,
497497
self.accepted_media_type,
498-
self.renderer_context
498+
{'style': {'template_pack': 'rest_framework/horizontal'}}
499499
)
500500

501501
def get_raw_data_form(self, data, view, method, request):

0 commit comments

Comments
 (0)