Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a ModelView in flask-admin

What's the right way to get the URL for a flask-admin ModelView?

Here's a very simple example:

my_admin_view.py

from flask.ext.admin.contrib.sqla import ModelView
from common.flask_app import app
from models import db, User, Role

admin = Admin(app, name="Boost Admin")

admin.add_view(ModelView(User,  db.session, category="model"))
admin.add_view(ModelView(Role,  db.session, category="model"))

my_admin_template.html

...
<p>Check out my user admin link:</p>

<a href="{{ url_for('modelview.user') }}">User view link</a>
{#                   ______________ 
                     what argument to pass in here??      #}
...

What's the correct argument to pass to url_for(...)?

I've tried modelview.user, my_admin_view.modelview.user, etc. None of them seem to resolve correctly, and I'd like to avoid hardcoding the link.

thanks!

like image 944
tohster Avatar asked Dec 06 '13 19:12

tohster


2 Answers

OK I figured it out after reading the source code for ModelView.

First, make sure that endpoints are named (it's possible to do it without named endpoints, but this makes the code much clearer):

from flask.ext.admin.contrib.sqla import ModelView
from models import db, User, Role

admin = Admin(app, name="Boost Admin")

admin.add_view(ModelView(User,db.session,category="model", endpoint="model_view_user"))
admin.add_view(ModelView(Role,db.session,category="model", endpoint="model_view_role"))

...now in the template, you can reference the basic model view as follows:

URL for User model default view is: {{model_view_user.index_view}} 
URL for Role model default view is: {{model_view_role.index_view}} 

The index_view function is defined here, and implements the default view for a flask admin ModelView.

like image 127
tohster Avatar answered Oct 17 '22 13:10

tohster


See the section Generating URLs in the Flask-Admin introduction.

It says to "use the lowercase name of the model as the prefix". Add a dot, and the name of the view.

  • index_view for the overview list.
  • create_view for creating a new row.
  • edit_view for modifying an existing row.

So you can easily do:

url_for('user.index_view')
url_for('role.create_view')
url_for('user.edit_view', id=1)
like image 37
florisla Avatar answered Oct 17 '22 15:10

florisla