Search code examples
flask-appbuilder

Flask App Builder url_for views


I am struggling on how to connect URL_for links in my app. I have a the basic skeleton app set up.

I wish to make a link to a function (that runs code) that is built in a view (MyView).

I essentially want to pass a variable (var1) to the view 'myview/method2/var1' and have that link showing in the ContactModelView.

Thanks

class MyView(BaseView):
route_base = "/myview"
@expose('/method2/<string:var1>')
@has_access
def fun_var(self, var1):
    # go to function_file and run function with var1
    param1, param2 = func_file.function(var1)
    self.update_redirect()
    return self.render_template('method3.html',
                                param1=param1,param2=param2, param3=prospects)

My models.py file has the following:

class Contact(Model):
id = Column(Integer, primary_key=True)
name = Column(String(150), unique = True, nullable=False)
var1 = Column(String(150))
contact_group_id = Column(Integer, ForeignKey('contact_group.id'))
contact_group = relationship("ContactGroup")

def prospect(self):
    return Markup(
        '<a href="'url_for("What To Put here?MyView.fun_var doesn't work")'">prospect</a>')

def __repr__(self):
    return self.name

I then have in views:

class ContactModelView(ModelView):
datamodel = SQLAInterface(Contact)

label_columns = {'contact_group':'Contacts Group'}
list_columns = ['name','var1','contact_group', 'action']

show_fieldsets = [
                    (
                        'Summary',
                        {'fields':['name','var1','contact_group', 'prospect']}
                    )
                 ]

Solution

  • In the documentation regarding BaseView, we see that

    Its constructor will register your exposed urls on flask as a Blueprint

    So make sure you add the view you created, in order to 'register the blueprint'. Use something like

    appbuilder.add_view_no_menu(MyView())
    

    You can run fabmanager list-views on the console to make sure your view was registered.

    As your endpoint requires a var1 parameter, you have to provide that to url_for. Something like this will work:

    class Contact(Model):
        var1 = Column(String(150))
        ...
        def prospect(self):
            return Markup(
                '<a href="' + url_for('MyView.fun_var', var1=self.var1) + '">prospect</a>')