Задать вопрос

Тел: +7 965 3737 888

415

Просмотров

2

Ответов

Hidden Forms

<p>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.
</p>
<p>Custom form example:
</p>
&gt;&gt;&gt; from django import newforms as forms
&gt;&gt;&gt; class MyForm(HiddenBaseForm, forms.Form):
...     some_field = forms.CharField()
...
&gt;&gt;&gt; f = MyForm({'some_field': 'test'})
&gt;&gt;&gt; f.as_hidden()
u'&lt;input type="hidden" name="some_field" value="test" id="id_some_field" /&gt;'
<p>With form_for_model:
</p>
SomeForm = forms.form_for_model(MyModel, form=HiddenBaseForm)

Вопрос полезен? Да0/Нет0
file_4084.py(872.0б)
None

Ответы (2):

Ответento:07.04.2010
Ответ полезен? Да0/Нет0

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

from django.utils.safestring import mark_safe

Ответdavid_bgk:25.11.2009
Ответ полезен? Да0/Нет0

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