Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top