How do you identify hidden form fields in a template

2 views
Skip to first unread message

davenaff

unread,
Jun 24, 2008, 7:03:48 PM6/24/08
to Django users
In a template, I'm using the equivalent of:
{% for field in form %}
{{ field.label_tag }}{{field}}
{% endfor %}

However, the labels of my hidden fields appear. Is there an easy way
to test if the field is using the HiddenInput widget (or an alternate
solution)?

Thanks!

bruno desthuilliers

unread,
Jun 25, 2008, 3:42:01 AM6/25/08
to Django users
What about "field.is_hidden" ?-)

NB: Python as pretty strong introspection features and a very handy
interactive shell, so most of the time the quick and easy way to learn
how to use a module / class / whatever is to play with it in the
shell.

Malcolm Tredinnick

unread,
Jun 25, 2008, 8:09:11 AM6/25/08
to django...@googlegroups.com

On Wed, 2008-06-25 at 00:42 -0700, bruno desthuilliers wrote:
> On 25 juin, 01:03, davenaff <daven...@gmail.com> wrote:
> > In a template, I'm using the equivalent of:
> > {% for field in form %}
> > {{ field.label_tag }}{{field}}
> > {% endfor %}
> >
> > However, the labels of my hidden fields appear. Is there an easy way
> > to test if the field is using the HiddenInput widget (or an alternate
> > solution)?
>
> What about "field.is_hidden" ?-)

I've found myself recently adding a method to my form classes (I use a
common base class) so that I can iterate over only the visible fields:

def visible_fields(self):
"""
Returns a list of BoundField objects that are not marked as
hidden.
"""
return [field for field in self if not field.is_hidden]

Then, where you've written {% for field in form %}, I write

{% for field in form.visible_fields %}

I also have a hidden_fields() method (which is almost identical to the
above) so that I can then include all the hidden fields in the final
form as well. I've used this on two recent projects I've worked on where
I have some custom form layout requirements and want to do it in the
template, rather than via a Python method.

Regards,
Malcolm


davenaff

unread,
Jun 25, 2008, 12:09:55 PM6/25/08
to Django users
Awesome, this is very helpful.

Thanks!

On Jun 25, 5:09 am, Malcolm Tredinnick <malc...@pointy-stick.com>
wrote:
Reply all
Reply to author
Forward
0 new messages