How to add a "Star" after the dengo model ModelForm CharField?

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

+5
source share
2 answers

I'm going to assume that you want this to happen automatically, so here is one of several 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 create an asterisk using CSS.

Or you can add an asterisk using CSS 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 is probably the best option if you want to do other things with the right field.

However, if you will not access the fields separately (for example, using {{form.as_p}}), then you can add the property to ModelForm:

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

, (, , CSS, , ( , ).

+23

jQuery, .

,

<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>

, .

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

, -

$('input,textarea,select').filter('[required]:visible').parent().parent().find("label").addClass("required_label");
0

All Articles