简体   繁体   English

url_for用于Flask-Admin中基于类的视图

[英]url_for for class-based views in Flask-Admin

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: 这是在Flask-Admin中注册的,如下所示:

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 ? 如何指定此类的URL而不是默认生成的名称all_rdps
  2. how do I use url_for to generate urls for these endpoints? 如何使用url_for为这些端点生成URL? url_for('admin.All_RDPs.testindex') , url_for('admin.All_RDPs') don't work. url_for('admin.All_RDPs.testindex')url_for('admin.All_RDPs')不起作用。

You can override the endpoint name by passing endpoint parameter to the view class constructor: 您可以通过将endpoint参数传递给视图类构造函数来覆盖端点名称:

 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,如:

 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. 默认情况下,ModelView还具有以下端点:.index_view,.create_view和.edit_view。 So, the following urls can be generated for a model named "User": 因此,可以为名为“User”的模型生成以下URL:

 # 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 来源: Flask-Admin快速入门

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM