Search code examples
flasksqlalchemyflask-sqlalchemyflask-wtformsflask-admin

Display inline model in the details page of the parent model? Flask, SQLAlchemy


I have a model A, which incorporates an inline model B that allows users to enter some texts. Currently, the data users added into the inline model can only be shown in the 'edit' page of the parent model A, but not in the 'details' page. Is there a way to solve this?

edit-page

enter image description here


Solution

  • Add the field in model B to the column_details_list (docs)

    Add the same field in model B to the column_formatters_detail dictionary (docs), specifying a formatter method that returns appropriate HTML.

    For example:

    from markupsafe import Markup
    
    class ExampleView(AdminView):
    
        # include the comments child field plus any parent fields from model A you want to show
        column_details_list =  ('name', 'last_name', 'comments')    
    
        def _comments_formatter(view, context, model, name):
            # model is parent model A
            _html = []
            if model.comments:
                #  return any valid HTML markup
                for _comment_model in model.comments:
                    # add html para per comment
                    _html.append(f'<p>User:{str(_comment_model.user)}, Comment:{_comment_model.comment}</p>')
    
                return Markup(''.join(_html))
    
        column_formatters_detail = {
            'comments': _comments_formatter
        }