Вопрос

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!

Это было полезно?

Решение

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.

Другие советы

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)

It should be

url_for('admin.user')

If you read the flask-admin docs here, for generating URLs, it clearly says:

If you want to generate a URL for a particular view method from outside, the following rules apply:

....

3. For model-based views the rules differ - the model class name should be used if an endpoint name is not provided. 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top