Search code examples
pythonflaskflask-wtforms

dynamically change SubmitField's label/value in html Flask WTForm


I have created a Flask WTForm. I used the form for Add/Edit/Delete purpose. I want dynamically change label/value of the SubmitField according to the purpose

Form Class

class UserForm(Form):
    username = StringField('User Name',validators=[validators.required(), validators.Length(max=32)])
    password = PasswordField('Password',validators=[validators.required(), validators.Length(min=8, max=16)])
    confirm_password = PasswordField('Confirm Password',validators=[validators.required(), validators.EqualTo('password', message='Both password fields must be equal !')])
    name = StringField('Name',validators=[validators.required(), validators.Length(max=32)])
    submit = SubmitField('Submit')

HTML Template

<title>User Form</title>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message[1] }}</li>
{% endfor %}</ul>
{% endif %}
{% endwith %}
<table height="100%" width="100%" >
<tr><td align="center" valign="middle">
<form method="post" action="/process/{{ option }}">
<table>
{{form.csrf }}
<tr><td>{{ form.username.label }}</td></tr>
<tr><td>
{% if option == "new" %}
    {{ form.username() }}
{% else %}
    {{ form.username(readonly=true) }}
{% endif %}
</td></tr>
<tr><td>{{ form.password.label }}</td></tr>
<tr><td>{{ form.password }}</td></tr>
<tr><td>{{ form.confirm_password.label }}</td></tr>
<tr><td>{{ form.confirm_password }}</td></tr>
<tr><td>{{ form.name.label }}</td></tr>
<tr><td>{{ form.name }}</td></tr>
{% if option == "new" %}
    {{ form.submit() }}  **submit label with 'New'
{% else %}
    {{ form.submit() }} **submit label with 'Edit'
{% endif %}
</table>
</form>
</td>
</tr>
</table>

Solution

  • Update the label at runtime in your view:

    For example:

    from wtforms import Label
    
    def some_view():
    
        _form = UserForm()
        _form.submit.label = Label(_form.submit.id, 'New' if option == 'new' else 'Edit')
    
        return render_template('index.html', form=_form)
    

    Edit November 2022

    It's even easier to simply modify the label's instance text property.

    def some_view():
        
        _form = UserForm()
        _form.submit.label.text = 'New' if option == 'new' else 'Edit'
        
        return render_template('index.html', form=_form)