Update text of submit button in wtforms
Asked Answered
D

4

8

I have a form, that will be used for a new submit and updates. My question is about the text of the submit button. I want to change the text to New submit and to New update, depending on the situation. This is purely informative.

class Interview(Form):
    ...
    submit = SubmitField('New submit')  

If possible, i want to avoid create a new class, with exactly same fields, only because of the text of submit.

Dumbbell answered 20/8, 2015 at 0:1 Comment(0)
S
9

The correct way to do this with mixins:

class InterviewMixin():
    ...

class InterviewSubmit(Form, InterviewMixin):
    submit = SubmitField('New submit')

class InterviewUpdate(Form, InterviewMixin):
    submit = SubmitField('New update')
Stochastic answered 25/8, 2015 at 14:48 Comment(0)
H
20

Old question, but for anyone else coming across this, an alternative is to just set it from code before rendering the template:

if is_submit:
    form.submit.label.text = 'New submit'
else:
    form.submit.label.text = 'New update'

return render_template(...)
Hashimoto answered 29/4, 2018 at 8:46 Comment(1)
This seems cleaner to just change the label than having to add a new form class as the approved answer suggest (though both work). Thanks.Hinckley
S
9

The correct way to do this with mixins:

class InterviewMixin():
    ...

class InterviewSubmit(Form, InterviewMixin):
    submit = SubmitField('New submit')

class InterviewUpdate(Form, InterviewMixin):
    submit = SubmitField('New update')
Stochastic answered 25/8, 2015 at 14:48 Comment(0)
C
0

I've solved the problem by not incorporating the submit button in the form definition, instead I add a submit button in the HTML, based on what label I want on it.

{% if pagetitle == 'Update' %}
   <p><input type="submit" name="btn" value="New Update"></p>
{% endif %}
{% if pagetitle == 'Submit' %}
   <p><input type="submit" name="btn" value="New Submit"></p>
{% endif %}

Using this way you can use the same form, and have different labels on the button, depending on which one should be used.

If you need you can use the same variable to set the action of the form, if you need to direct to different views.

Or you can use the value of the button in the view.

if flask.request.form['btn'] == 'New Update':
   ...
elif flask.request.form['btn'] == 'New Submit':
   ...
Clarinda answered 25/8, 2015 at 8:21 Comment(0)
T
-1

The correct way would be to make two forms and check which submit button is pressed at server side.

if submit_form.validate_on_submit() and submit_form.any_field.data:
        print "submit_form submit button is Pressed"
elif update_form.validate_on_submit() and update_form.any_field.data:
        print "update_form submit button is submitted"
Tripersonal answered 31/5, 2016 at 12:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.