Search code examples
pythonflask-wtforms

How can I add a value to a WTForms Submit field without changing its display label?


When I set a value for the field it changes the display label of the field. I'm using FlaskWTForms and the field is defined as:

class EditMultilpeChoiceQuestion(FlaskForm):

    submit_update = SubmitField(name="submit_update", label="Update question")

In the Jinja template the code to display the field is:

{{ form.submit_update(class="btn btn-primary btn-sm" value=question['database_id']) }}

Is this example the value of question['database_id'] is 10 and the field display as:

button display with value parameter added

If I don't have the value=question['database_id'] the field displays as I want:

button display with no value parameter

any suggestions much appreciated.


Solution

  • The widget used to render a submit field is a SubmitInput, Github source, as shown below:

    class SubmitInput(Input):
        """
        Renders a submit button.
    
        The field's label is used as the text of the submit button instead of the
        data on the field.
        """
    
        input_type = "submit"
    
        def __call__(self, field, **kwargs):
            kwargs.setdefault("value", field.label.text)
            return super().__call__(field, **kwargs)
    

    Note the comment:

    The field's label is used as the text of the submit button instead of the data on the field.

    See simple test code below:

    from wtforms.fields import SubmitField
    from wtforms.form import Form
    
    
    class F(Form):
        a = SubmitField(label="Update question")
    
    
    def test_submit_field():
        # Pass no args
        _html = F().a()
        print(_html)
        assert _html == """<input id="a" name="a" type="submit" value="Update question">"""
    
        # assigning the value clears the label
        _html = F().a(value=10)
        print(_html)
        assert _html == """<input id="a" name="a" type="submit" value="10">"""
    
        # assign label and value
        _html = F().a(label="Hello World", value=10)
        print(_html)
        assert _html == """<input id="a" label="Hello World" name="a" type="submit" value="10">"""
    
    
    if __name__ == "__main__":
        test_submit_field()