Login

Hidden Forms

Author:
insin
Posted:
July 14, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks 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.