|
| 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 | + |
| 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 | + |
| 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 | + |
| 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 |
|
0 commit comments