Reputation: 12605
I have created a simple form, view and template file as described below. One of my form field is required (url1) and one is optional (comment1). In my template, I would like to display that field tags for these two fields differently based on if they are optional or not (for example: Required in red, Optionali in green). How can I do that?
Ideally there would be a boolean value in the form that looked like this: form.url1.required_flag
Here is my form:
class myForm(forms.Form):
url1 = forms.URLField(max_length=255, label='URL #1', required=True)
comment1 = forms.CharField(max_length=255, label='Comment #1', required=False)
The view for this form is very simple. Nothing fancy.
Here is the relevant part of the template file:
<tr>
<td width="100" align="right">
<div class="field_label">
{{ form.url1.label_tag }}:
</div>
</td>
<td width="300">
<div class="form_element_input">
{{ form.url1 }}
</div>
</td>
<td width="100" align="right">
<div class="field_label">
{{ form.comment1.label_tag }}:
</div>
</td>
<td width="300">
<div class="form_element_input">
{{ form.comment1 }}
</div>
</td>
</tr>
Upvotes: 1
Views: 2363
Reputation: 6335
Take a look at required_css_class
class myForm(forms.Form):
required_css_class = 'required'
url1 = forms.URLField(max_length=255, label='URL #1', required=True)
comment1 = forms.CharField(max_length=255, label='Comment #1', required=False)
You can reach css classes with form.field.css_classes
or they get printed out if you use any of as_p
, as_table
methods.
Upvotes: 0
Reputation: 2738
{% if form.comment1.field.required %}
//do something
{% else %}
//do something else
{% endif %}
Should help
But again, you can pretty much use CSS to just color the comment with one color and url with another. I dont think you need to use required for that
Upvotes: 3