Flask-Admin - Customizing views
Asked Answered
G

1

7

I'm developing a web-app using Flask and pyMongo, and I've recently started to integrate the Flask-Admin module (1.0.4), given the fresh mongodb support.

All is smooth and fine when using ModelViews, but when it comes to subclassing a BaseView I simply can't get it working.

Here is my setup:


user_view = Admin(app, name='User stuff', url="/user", endpoint="user")


class ProfileForm(wtf.Form):
    username = wtf.TextField('Username', [wtf.Required()])
    name = wtf.TextField('Name', [wtf.Required()])


class Profile(BaseView):
    @expose('/', methods=('GET', 'POST'))
    def profile(self):
        user = User(uid) # gets the user's data from DB
        form = ProfileForm(request.form, obj=user)
        if form.validate_on_submit():
            data = form.data
            user.set(**data)
            user.save()
            flash("Your profile has been saved")
        else:
            flash("form did not validate on submit")
        return self.render('user/profile.html', form=form, data=user)

user_view.add_view(Profile(name='Profile', url='profile'))

When submitting the form, wtforms does not report any error (unless there is any) but the validation does not return to my profile view (the else: branch is always executed)

There is no way I could find to make this work, inspite having thoroughly scanned flask-admin documentation, source code and examples.

Could anybody suggest how I could fix my code, or work around this problem ?

Grevera answered 15/1, 2013 at 23:36 Comment(0)
G
6

I have suspicion that form is getting submitted using GET method instead of POST or Flask-WTF CSRF check fails.

Here's small gist I made with your sample code. It works as expected: https://gist.github.com/4556210

Few comments:

  1. Template uses some Flask-Admin library functions to render the form. You don't have to use them if you dont want to;
  2. Uses mock user object
  3. Put template under templates/ subdirectory if you want to run the sample.

In either case, Flask-Admin views behave exactly same way like "normal" Flask views, they're just organised differently.

Greyso answered 17/1, 2013 at 14:20 Comment(2)
Thanks Joes. You're right, the problem was in the Form, I was reusing a proper form from another module, but the template was omitting some mandatory fields.Thank you also for flask-admin, it's a great library !Grevera
@Greyso Just in case you know the answer, I started a bounty on this question. :)Frosted

© 2022 - 2024 — McMap. All rights reserved.