简体   繁体   中英

Django label_tag required asterisk

I am currently working on some Django templates and would like to put an asterisk after the label of required fields.

First of all I have found this syntax which works just fine but it makes me type a lot of code that is not required without the required asterisk.

<div>
    {{ field.errors }}
    <label for="{{ field.auto_id }}">
        {% if field.field.required %}<span class="required">{{ field.label }}</span>
        {% else %}{{ field.label }}{% endif %}
    </label>
    {{ field }}
</div>

This is the code I currently have in my template:

<div>
    {{ field.errors }}
    {{ field.label_tag }}{{ field }}
</div>

This way it saves a lot of code to write, but I can't figure out how to get the asterisk after the label with a required field.

Could someone help me with this? If you need some more info feel free to ask.

您是否尝试过在表单上设置required_css_class = 'something' (请参见此处 ),然后使用CSS在标签上添加一个红色星号

Consider writing a template tag that takes in field and returns field.label suffixed with an asterisk if the field is required, and field.label if not. And you can use like so:

<div>
    {{ field.errors }}
    {{ field | append_ast_if_req }}
    {{ field }}
</div>

Your template tag can be:

@register.filter
def append_ast_if_req (field):
    if field.field.required:
         return field.label + '*'
    else:
         return field.label

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM