Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can model views in Flask-Admin hyperlink to other model views?

Tags:

python

flask

Let's suppose we have a model, Foo, that references another model, User - and there are Flask-Admin's ModelView for both.

On the Foo admin view page

enter image description here

I would like the entries in the User column to be linked to the corresponding User model view.

Do I need to modify one of Flask-Admin's templates to achieve this?

(This is possible in the Django admin interface by simply outputting HTML for a given field and setting allow_tags (ref) True to bypass Django's HTML tag filter)

like image 708
wodow Avatar asked Jun 18 '13 16:06

wodow


2 Answers

Some example code based on Joes' answer:

class MyFooView(ModelView):

    def _user_formatter(view, context, model, name):
        return Markup(
            u"<a href='%s'>%s</a>" % (
                url_for('user.edit_view', id=model.user.id),
                model.user
            )
        ) if model.user else u""

    column_formatters = {
        'user': _user_formatter
    }
like image 114
wodow Avatar answered Oct 23 '22 10:10

wodow


Use column_formatters for this: https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_formatters

Idea is pretty simple: for a field that you want to display as hyperlink, either generate a HTML string and wrap it with Jinja2 Markup class (so it won't be escaped in templates) or use macro helper: https://github.com/mrjoes/flask-admin/blob/master/flask_admin/model/template.py

Macro helper allows you to use custom Jinja2 macros in overridden template, which moves presentational logic to templates.

As far as URL is concerned, all you need is to find endpoint name generated (or provided) for the User model and do url_for('userview.edit_view', id=model.id) to generate the link.

like image 21
Joes Avatar answered Oct 23 '22 10:10

Joes