Add a * to required field's label

Question:

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?

Asked By: Taxellool

||

Answers:

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 %}
Answered By: davidism

I’ve tried to find a better answer to this question and in my case this css trick worked very well and I did not have to alter anything else:

add a file to the-flask-wtf-project/app/static/styles/custom.css

with the following content in it:

div.required label:after {
    content: " *";
    color: red;
}

Then make sure to include the css in base.html (or all your templates using forms) inside the {% block scripts %}

    <link rel="stylesheet" type="text/css" href="{{url_for('static',filename='styles/custom.css') }}">

I still consider myself a newbie so if this tips is off somehow please chime in.

Just my 2 cents, that I was very pleased with and could not find easily on any other thread here or elsewhere.

Answered By: Henrik Andreasson

Following Henrik Andreasson‘s answer (thanks to his suggestion), I would like to add some more precision, because I spent few hours understanding how to avoid to do macros, like on the answer of davidism.

In the html file, you should add the attribute required:

<label for="{{ field.name }}" required="">

In my case, I was also doing a project on Flask with WTForms, so instead of what was written above, I did:

{{ form.field.label(required=form.field.flags.required) }}

In the css file, you should add:

label[required]:after {
    content: " *";
}

which means:
after all the tags label containing the attribute required, add all the things in the dictionary.

Hope it helps.

Answered By: kiki270