url_for for class-based views in Flask-Admin
Asked Answered
C

1

12

I have a class-based Admin view:

class All_RDPs(BaseView):
    @expose('/')
    def index(self):
        return 'ok1'
    @expose('/test')
    def testindex(self):
        return 'ok2'

which is registered with Flask-Admin like so:

admin.add_view(All_RDPs(name='dep_rdp'))

and then is viewable from the browser like so:

http://localhost/admin/all_rdps/
http://localhost/admin/all_rdps/test

the question is:

  1. how do I specify the URL for this class instead of the default generated name all_rdps?
  2. how do I use url_for to generate urls for these endpoints? url_for('admin.All_RDPs.testindex'), url_for('admin.All_RDPs') don't work.
Chlores answered 11/11, 2015 at 12:57 Comment(0)
C
22

You can override the endpoint name by passing endpoint parameter to the view class constructor:

admin = Admin(app)
admin.add_view(MyView(endpoint='testadmin'))

In this case, you can generate links by concatenating the view method name with an endpoint:

url_for('testadmin.index')

If you don't override the endpoint name, the lower-case class name can be used for generating URLs, like in:

url_for('myview.index')

For model-based views the rules differ - the model class name should be used if an endpoint name is not provided. The ModelView also has these endpoints by default: .index_view, .create_view, and .edit_view. So, the following urls can be generated for a model named "User":

# List View
url_for('user.index_view')

# Create View (redirect back to index_view)
url_for('user.create_view', url=url_for('user.index_view'))

# Edit View for record #1 (redirect back to index_view)
url_for('user.edit_view', id=1, url=url_for('user.index_view'))

Source: Flask-Admin quickstart

Coffelt answered 11/11, 2015 at 13:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.