Debian Codegraph @

docs/topics/html-and-forms.md

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