Wednesday, September 29, 2010

Suppressing field in template for ChoiceField with only one option.

I ran into an interesting forms issue today which I came up with a solution for. Now I'm wondering if there's a better way.

Situation:

I have a forms.Form with several fields in it, including a ChoiceField. The values in this ChoiceField are dependent on what the user has access to. Many users will only have one possible option.

Desire:

Users with multiple options will see the ChoiceField in the form.
Users with only one choice will not see the ChoiceField, but the single possible value will be available during form validation.

Solution:

In the event that there's only one option, the __init__ of the form sets the field's initial value, changes the input widget to a HiddenInput, and sets the label to an empty string.

This works fine, but seems a little hacky. Has anyone come up with a cleaner option?

Thanks,
Shawn

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment