Have your forms descend from this BaseForm if you need to be able to render a valid form as hidden fields for re-submission, e.g. when showing a preview of something generated based on the form's contents.
Custom form example:
>>> from django import newforms as forms
>>> class MyForm(HiddenBaseForm, forms.Form):
... some_field = forms.CharField()
...
>>> f = MyForm({'some_field': 'test'})
>>> f.as_hidden()
u'<input type="hidden" name="some_field" value="test" id="id_some_field" />'
With form_for_model
:
SomeForm = forms.form_for_model(MyModel, form=HiddenBaseForm)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | from django import newforms as forms
from django.newforms.forms import BoundField
class HiddenBaseForm(forms.BaseForm):
"""
Adds an ``as_hidden`` method to forms, which allows you to render
a form using ``<input type="hidden">`` elements for every field.
There is no error checking or display, as it is assumed you will
be rendering a pre-validated form for resubmission, for example -
when generating a preview of something based on a valid form's
contents, resubmitting the same form via POST as confirmation.
"""
def as_hidden(self):
"""
Returns this form rendered entirely as hidden fields.
"""
output = []
for name, field in self.fields.items():
bf = BoundField(self, field, name)
output.append(bf.as_hidden())
return u'\n'.join(output)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Updated to be 1.1 compliant:
#
To use david_bgk's snippet, you need to import
mark_safe
as well:#
Please login first before commenting.