bocca
bocca

Reputation: 1995

Custom django form fields

I am trying to get if required "*" within lable tag. Somewhat close to this

<label for="id_name"><strong>Name</strong> <em>*</em></label>

With label_tag

{{ field.label_tag }}

it generates as

<label for="id_city">City</label>

this begins and closes label tag, how to insert "*" before closing

this hack seems to work,

<label for="id_{{ field.label }}">{{ field.label }} 
{% if field.field.required %}<em>*</em>{% endif %}</label> 

it is not functional as field label id would different than field label, as "name" not "Name"

Upvotes: 1

Views: 369

Answers (2)

Googol
Googol

Reputation: 2923

template:

<label for="{{ user_form.first_name.id_for_label }}" class="{{ user_form.first_name.css_classes }}">{{ user_form.first_name.label }}{{ user_form.label_suffix }}</label>

forms.py:

class UserChangeForm(DjangoUserChangeForm):
    error_css_class = 'field_error'
    required_css_class = 'field_required'

CSS:

.field_required:after {
    content: " *";
}

Upvotes: 0

Van Gale
Van Gale

Reputation: 43922

Your code is very similar to this Django snippet. A comment there suggests using:

    <label for="{{ field.auto_id }}">

instead of your:

    <label for="id_{{ field.label }}">

You can also try this snippet as an alternative.

Upvotes: 2

Related Questions