How add a 'Star *' after a django ModelForm CharField?

◇◆丶佛笑我妖孽 提交于 2020-01-01 10:13:30

问题


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


回答1:


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




回答2:


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");


来源:https://stackoverflow.com/questions/12235201/how-add-a-star-after-a-django-modelform-charfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!