开发者

Using WTForms' populate_obj( ) method with Flask micro framework

开发者 https://www.devze.com 2023-03-09 11:53 出处:网络
I have a template which allows the user to edit their user information. <form method=\"post\"> <table>

I have a template which 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.pas开发者_JAVA百科sword.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 for handling such edits by the user. The database I am currently using is MongoDB with the MongoKit module. I have only been able to do up to this so far in the view function, yet with 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 am going through populate_obj(obj) for this purpose. I couldn't find much help in this matter. What should I do in order to get populate_obj() working?


UserForm should have request.form passed into it to populate it with the values available in the POST request (if any).

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


Are you using Flask-WTF? If so, check out the following sample code:

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

Specifically, you would:

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

Bottom line, if you're using Flask-WTF, I'm not sure what your question is. If you aren't using Flask-WTF, use Flask-WTF.


In case of Flask-WTF, you can write like

form = UserForm(obj=user)

Thant will work!

0

精彩评论

暂无评论...
验证码 换一张
取 消