Yassine Faris
Yassine Faris

Reputation: 991

Flask admin view and flash message

I am trying to use the flash system to display a message to the user in the admin view if he doesn't have certain right.
The following almost work, but the message is only display the next time the user change the page.

from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask import flash, Flask
from flask_admin.babel import gettext


db = SQLAlchemy()


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username




class UserView(ModelView):
    def check_can_create(self):
        can_create = False
        if can_create:
            print("wat")
            return True
        else:
            print("flash")
            flash(gettext("You can't create other user"), 'error')
            return False

    can_create = property(check_can_create)



admin = Admin()
admin.add_view(UserView(User, db.session))

app = Flask(__name__)
app.secret_key = b'ninja'
db.init_app(app)
db.app = app
db.create_all()
admin.init_app(app)

app.run()  # Goto 127.0.0.1:5000/admin

I think it's du to the fact that flask first fetch all the flash message then check the can_create/delete flag of the model_view.
Do someone have a solution?

Upvotes: 1

Views: 2143

Answers (1)

Yassine Faris
Yassine Faris

Reputation: 991

Used the render method of model views to bypass my problem:

class UserView(ModelView):
    def render(self):
        if not self.can_create:
            flash(gettext("You can't create other user"), 'error')

        return super(UserView, self).render()

Upvotes: 2

Related Questions