Search code examples
pythonflaskwtformsflask-wtforms

Add a * to required field's label


I want to add a '*' before (or after) label's text in case the filed is required.

I can do this now by using this in my template:

{% for field in form %}
    <label for="{{ field.name }}">
    {{ '*' if field.flags.required }}{{ field.label.text }} :
    </label>
    {{ field }}
{% endfor %}

Is there some better way than this, at least a way to avoid adding label element manually?


Solution

  • That's how you do it, there is no simpler way than by checking the flag and then outputting what you want. You can change the text of the label somewhat more directly, though. You could also make a macro out of it so you don't need to copy and paste as much for each field in each template. Create a template "forms.html":

    {% macro form_field(field) %}
        {% if field.flags.required %}{{ field.label(text='*' + field.label.text) }}
        {% else %}{{ field.label }}{% endif %}:
        {{ field }}
    {% endmacro %}
    

    Then use it in other templates:

    {# import the macro at the top of the template #}
    {% from "forms.html" import form_field %}
    
    {# use it in your for loop #}
    {% for field in form %}
        {{ form_field(field) }}
    {% endfor %}