How to reference ModelView in flask-admin

What is the right way to get the url for ModelView ModelView ?

Here is 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 is the right argument to go to url_for(...) ?

I tried modelview.user , my_admin_view.modelview.user etc. None of them seem to resolve correctly, and I would like to avoid hard-coding the link.

thanks!

+6
source share
3 answers

OK. I understood this after reading the source code of ModelView.

First, make sure the endpoints are named (it is possible to do this without named endpoints, but this makes the code more understandable):

 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 refer to the representation of the base model 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 index_view defined here and implements the default view for the ModelView flag manager.

+8
source

See Creating URLs in Introduction to Flask-Admin .

It states that "use the lower registration name of the model as a prefix." Add a period and a name for the view.

  • index_view for the overview list.
  • create_view to create a new row.
  • edit_view to modify an existing row.

So you can easily:

 url_for('user.index_view') url_for('role.create_view') url_for('user.edit_view', id=1) 
+4
source

It should be

 url_for('admin.user') 

If you read flask-admin docs here , to create the 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. 
0
source

Source: https://habr.com/ru/post/959499/


All Articles