0

Possible duplicate: WTForms - dynamic labels by passing argument to constructor?

I'm creating a form using WTForms and Flask that lets users enter a new contact:

class ContactForm(Form):
    firstName = StringField("First Name", [validators.Required("Please enter your first name.")])
    lastName = StringField("Last Name", [validators.Required("Please enter your last name.")])
    email = StringField('Email')
    phoneNo = StringField('Phone #')
    notes = StringField('Notes', widget=TextArea())
    submit = SubmitField("Create Contact")

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)

I'd like to use this form when the user creates a new contact and also when the user wants to edit an existing contact, and so I need to be able to change some of the labels displayed to the user dynamically (in particular I need to change the text on the submit button). I'd like to pass in a string to the constructor for that purpose, but I'm not that familiar with either Python or WTForms. Can someone help me figure out how to do it?

Community
  • 1
  • 1
Adam
  • 8,752
  • 12
  • 54
  • 96

1 Answers1

0

I'm doing something similar at the moment. I wonder what your HTML template looks like. I used my template to worry about the submit button text. Here is the class within init.py >>>

from flask import Flask, render_template
from wtforms import Form, StringField, validators
class InputForm(Form):
    something = StringField(u'Enter a website', [validators.required(), validators.url()])
@app.route('/somewhere/', methods=['GET', 'POST'])
def index():
  form = InputForm(request.form)
  if request.method == 'POST' and form.validate():
    url = form.something.data
    someAction = compute(url)
    return render_template("view_output.html", form=form, someAction = someAction)
  else:
    return render_template("view_input.html", form=form)

Here is how I leverage it in the template>>>

<form method=post action="">
    <div class="form-group">
        <label for="thaturl">Website Adress</label>
        {{ form.something(style="margin-top: 5px; margin-bottom: 5px; height: 26px; width: 292px; margin-right: 15px;") }}
    </div>
    <button type="submit" class="btn btn-primary" aria-label="Left Align" style="margin-top: 5px; margin-bottom: 5px; height: 44px; margin-right: 15px">
        <span class="glyphicon glyphicon-signal" aria-hidden="true"></span>
        Check My Site
    </button>
    </form>
Kevin
  • 116
  • 1
  • 5
  • Making the button part of the template would work, the problem is that the button is part of the Contact form itself. To make it show up in my template all I do is write `{{ form.submit }}`. What I ended up doing is just writing another template, but doing so involved a lot of copy/pasting which is never a good thing. – Adam Mar 12 '16 at 04:22