1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 | from django import newforms as forms
class DynamicFieldSnippetForm(forms.Form):
"""DynamicFieldSnippetForm - declare a field dynamically in a form.
The weight field is required. The height field is optional and
not included on the form unless requested.
>>> print DynamicFieldSnippetForm()
<tr><th><label for="id_weight">Weight:</label></th><td><input type="text" name="weight" id="id_weight" /></td></tr>
>>> print DynamicFieldSnippetForm(request_height=True)
<tr><th><label for="id_weight">Weight:</label></th><td><input type="text" name="weight" id="id_weight" /></td></tr>
<tr><th><label for="id_height">Height:</label></th><td><input type="text" name="height" id="id_height" /></td></tr>
>>> print DynamicFieldSnippetForm({'height':174, 'weight':122}, request_height=True)
<tr><th><label for="id_weight">Weight:</label></th><td><input type="text" name="weight" value="122" id="id_weight" /></td></tr>
<tr><th><label for="id_height">Height:</label></th><td><input type="text" name="height" value="174" id="id_height" /></td></tr>
>>>
"""
def __init__(self, *args, **kwargs):
request_height = kwargs.pop('request_height', False)
super(DynamicFieldSnippetForm, self).__init__(*args, **kwargs)
if request_height:
self.fields['height'] = forms.CharField(required=False)
weight = forms.CharField()
if __name__ == '__main__':
import doctest
doctest.testmod()
|
Comments
If you are also giving dynamic names to your dynamic fields and thusly need to generate dynamic
clean_FOO()methods, the following lambda trick may give you a hint on how to proceed:#
Apologies for the incomplete example above. If you need
selfavailable to your helper function, you'll need an extra wrapper:There may be a better way to accomplish the above. I'm still learning.
#
There is, and it's called closures. Not much shorter, but certainly more readable.
#