views:

65

answers:

3

Hi,

I've got a dynamic form that contains either one or several MultipleChoiceFields or ChoiceFields. I want to display an instruction to the user, e.g. for ChoiceField: "Select one of the following", and for MultipleChoiceField: "Select any of the following"

How can I do this? I tried subclassing each of these fields, but I couldn't get the value back out in the template.

Thanks

EDIT

I tried something like:

class MultiWithInstruction(forms.MultipleChoiceField):
    def __init__(self, instruction=None, **kwargs):
        self.instruction=instruction
        return super(MultiWithInstruction, self).__init__(**kwargs)

I couldn't retrieve the value of 'instruction' in the template.

A: 

Why not just use help_text?

class MyForm(forms.Form):
    my_field = forms.MultipleChoiceField(help_text='Pick one of these', ....)

And then in the template you could do something like this:

<p>{{ field.label_tag }}: {{ field }}</p>
{% if field.help_text %}<p class="help_text">{{ field.help_text|safe }}</p>{% endif %}
Nimmy Lebby
i'm already using that for something else
PeterP
A: 

You can set the label value in your form field:

myfield = forms.MultipleChoiceField(label='Select any of the following')
Martin
i'm already using that too. i need to add an extra field that's like a label or help text
PeterP
Form instances are just like any Python object. You can set an attribute to be anything you like. For example, say you create your form as form = MyForm(), you can then just set form.additional_label = 'This is my text'. In your template, you can call {{ form.additional_label }} and output the value.
Martin
A: 

I had the same problem. I couldn't find an easy way (without overriding a lot of stuff from django.forms) so I came up with this quick-and-dirty solution.

Define a new template filter, that splits a string into a list, given a separator; see this simple snippet by Ciantic. Save the snippet as templatetags/whatever_name.py.

In forms.py, fill the help_text attribute of the field with your help and instruction strings, separated by '#' (you can choose whatever separator you want, of course); something like

my_field = forms.MultipleChoiceField(help_text = '%s#%s' % (help_string, instruction_string), ...)

help_text is a string (already marked safe), so you can't put a list in it (this is why the custom split filter is needed).

And this is an example of a template that shows help and instruction strings for each field in the form:

{% load whatever_name %}

{% for field in form %}
    help: {% filter split:"#"|first %}{{ field.help_text }}{% endfilter %}
    instruction: {% filter split:"#"|last %}{{ field.help_text }}{% endfilter %}
{% endfor %}

Obviously, you can't use as_p, as_table and as_ul to render the form.

martip