Houman
Houman

Reputation: 66320

How to check if a form field is required?

Within my model I have defined a required field class like this:

class Contact(models.Model):
    last_name = models.CharField(_(u"Last Name"), max_length=50)

For the form I am simply using the ModelForm to keep it simple:

class ContactsForm(ModelForm):
   class Meta:
        model = Contact

I understand there are third-party-mods helping with rendering forms, however going plain for now to see when I hit the limitations, so I tried this:

            <tr>
                <td>
                    {{form.last_name.label}}:
                </td>
                <td>
                    {{form.last_name}}
                    {% if  form.last_name.required %}(*){% endif %}
                </td>
            </tr>

Surprisingly I don't get to see the (*) even though its a required field.

What am I missing?

Upvotes: 1

Views: 2644

Answers (3)

Hrayr Stepanyan
Hrayr Stepanyan

Reputation: 43

If your field is an instance of BoundField then you can use property required of the field. Lets say you iterate on the form for fields: On each iteration you will have each field in order you put in the Form class.

So, the code for the Form class will look like this.

class Form(forms.ModelForm):
    name = forms.CharField(max_length=50)
    last_name = forms.CharField(max_length=50, required=False)

And your iteration on the form in the template could look like this:

...
{% for field in form %}
    {{ field }}
    <label {% if field.field.required %}class="required"{% endif %}>{{ field.label }}</label>
{% endfor %}
...

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599590

I can't test this now, but I'm pretty sure you need form.last_name.field.required - form.last_name is an instance of BoundField, and it has a field property which points to the original CharField, which in turn contains the required property.

Upvotes: 8

machaku
machaku

Reputation: 1196

I think tou can override the default label for required fields. I mean something like

class ContactsForm(ModelForm):
   last_name = CharField(label='Last Name (*)')

   class Meta:
       model = Contact

Upvotes: 0

Related Questions