Using the populate_obj () WTForms method with micro framework

I have a template that allows the user to edit their user information.

<form method="post">
    <table>
        <tr>
            <td>Username:</td>
            <td>{{user['username']}}</td>
        </tr>
        <tr>
            <td>New Password:</td>
            <td> <input type="password" name="password"></td>
            <td>{% if form.password.errors %} {{form.password.errors}} {% endif %}<td>
        </tr>
        <tr>
            <td>Re-enter Password:</td>
            <td> <input type="password" name="confirm_password">
            </td>
        </tr>
        <input type='hidden' name='username' value="{{user['username']}}">
        <tr>
            <td><input type="submit" value="Submit"></td>
        </tr>
    </table>
</form>

I also have a view function to handle such changes by the user. I am currently using the MongoDB database with MongoKit . Until now, I could still do this in the view function, but no luck.

def edit():
    username = request.args.get('user')
    user = User.find_one({'username':username}) # Is this a correct way of doing it?
    form = UserForm(**what should be placed here?**, obj=user)

    if request.method == 'POST' and form.validate():
        form.populate_obj(user)
        user.save()
        return 'updated'
    return render_template('edituser.html', form=form, user=user)

I go through populate_obj (obj) for this purpose. I could not find much help in this matter. What to do to work populate_obj()?

+5
source share
3 answers

UserForm request.form, , POST ( ).

form = UserForm(request.form, obj=user)
+15

Flask-WTF? , :

https://github.com/sean-/flask-skeleton/blob/master/skeleton/modules/aaa/views.py#L13

, :

def edit():
    form = UserForm()
    if form.validate_on_submit():
        # Commit your form data

, Flask-WTF, , . Flask-WTF, Flask-WTF.

+6

In the case of Flask-WTF, you can write as

form = UserForm(obj=user)

Tant will work!

+1
source

All Articles