Login

Hidden Forms

Author:
insin
Posted:
July 14, 2007
Language:
Python
Version:
.96
Tags:
newforms form baseform hidden
Score:
3 (after 3 ratings)

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

  1. Bootstrap button dropdown widget (replaces forms.Select) by benjaoming 2 years, 8 months ago
  2. SectionedForm by marinho 6 years, 10 months ago
  3. Validation for full e-mails (e.g. "Joe Hacker <joe@hacker.com>") by akaihola 3 years, 4 months ago
  4. DRYer instantiation of Forms by SmileyChris 6 years ago
  5. Changing the look of newforms as_table with a custom BaseForm by bikeshedder 7 years, 10 months ago

Comments

david_bgk (on November 25, 2009):

Updated to be 1.1 compliant:

from django import forms
from django.forms.forms import BoundField

class HiddenBaseForm(forms.BaseForm):
    def as_hidden(self):
        """
        Returns this form rendered entirely as hidden fields.
        """
        return mark_safe(u'\n'.join(BoundField(self, field, name).as_hidden() \
                                    for name, field in self.fields.items()))
    as_hidden.needs_autoescape = True

#

ento (on April 7, 2010):

To use david_bgk's snippet, you need to import mark_safe as well:

from django.utils.safestring import mark_safe

#

Please login first before commenting.