Question

i have some necessary fields in my django ModelForm. How can i add a red star (*) after the required fields ?

Was it helpful?

Solution

I'm going to assume you want this to happen automatically, so here's one of a few different ways:

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

Then you can style the asterisk using CSS.

Or, you can add the asterisk using CSS instead if you want:

<style type="text/css">
    span.required:after { content: '*'; }
</style>
{% for field in form %}
    <label for="{{ field.auto_id }}">
    {% if field.field.required %}
        <span class="required">{{ field.label_tag }}</span>
    {% else %}
        {{ field.label_tag }}
    {% endif %}
    </label>
{% endfor %}

This one is probably a better option if you want to do other things with the required field as well.

However, if you will not be accessing the fields individually (such as using {{ form.as_p }}), then you can add a property to your ModelForm:

class FooForm(forms.ModelForm):
    required_css_class = 'required'

That will define all fields that are required as having the 'required' class (and thus, you can use the CSS code I mentioned above to add an asterisk (or whatever else you want to do with it).

OTHER TIPS

You can also use jQuery in order to select the label or append to it.

for example if you have this bootstrap form

<form class="form-horizontal">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail3" required="required">
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword3">
    </div>
  </div>
</form>

Then if you want to add the star to the required fields.

$('input,textarea,select').filter('[required]').parent().parent().find("label").append("*");

Also you may want to specify a class for the required fields labels so you can make them bold or something

$('input,textarea,select').filter('[required]:visible').parent().parent().find("label").addClass("required_label");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top