Django 1.2: Custom form field?
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:开发者_Go百科 "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.
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 %}
You can set the label value in your form field:
myfield = forms.MultipleChoiceField(label='Select any of the following')
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.
精彩评论