Python Forum
Pre-populating WTForms form values for edit - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: Pre-populating WTForms form values for edit (/thread-24652.html)



Pre-populating WTForms form values for edit - danfoster - Feb-25-2020

I'm a newbie, trying to use Flask with WTForms. My objective is to create a form to edit a user record returned from a database. The following code, mocking the db with an instance of the User class, executes without error for the /form route. No problem. But the form values do not contain pre-populated data for the user to edit!

The /test route returns: TypeError: 'str' object is not callable.

I just want the form to display user data for editing.
Any help would be greatly appreciated.

Here's code from my .py file:

class LogInForm(FlaskForm):
    username = StringField('username', [validators.DataRequired()])
    password = PasswordField('password', [validators.DataRequired()])

class User():
    def __init__(self, name, pwd):
        self.name = name
        self.pwd = pwd

@app.route('/test', methods=['GET', 'POST'])
def test():
    found_user = User("Moe", "2222")
    form = LogInForm(obj=found_user)
    return render_template('test.html',user=found_user, form=form)


@app.route('/form', methods=['GET', 'POST'])
def form():
    user = User("Moe", "2222")

    form = LogInForm(obj=user)

    if form.validate_on_submit():
        return f'The form has been submitted. Username {form.username.data}. Password{form.password.data}'
    return render_template('forms.html', form=form)
Here's the template for the /form route:

form  method = "POST" action="{{ url_for('form') }}">
    {{ form.csrf_token }}
    {% for field in form %}
    <p>
        {{field.label}}
        {{field}}
    </p>
    {% endfor %}
    <input type="submit" value="Submit">
</form>
</body>
Here's the template for the /test route:

<body>
    {% from "_formhelpers.html" import render_field %}
    <form method="post">
        <dl>
            {{ render_field(user.name) }}
            {{ render_field(user.pwd) }}
        </dl>
        <p><input type="submit" value="Submit">
    </form>
<a href="/">Go to home page.</a>
</body>