For GenericReferenceField and LazyGenericReferenceField

    See Also
    --------
    diff_formatter

def generic_ref_formatter(view, context, model, name, lazy=False):
    """
    For GenericReferenceField and LazyGenericReferenceField

    See Also
    --------
    diff_formatter
    """
    try:
        if lazy:
            rel_model = getattr(model, name).fetch()
        else:
            rel_model = getattr(model, name)
    except (mongoengine.DoesNotExist, AttributeError) as e:
        # custom_field_type_formatters seems to fix the issue of stale references
        # crashing pages, since it intercepts the display of all ReferenceField's.
        return Markup(
            '<span class="label label-danger">Error</span> <small>%s</small>' % e
        )

    if rel_model is None:
        return ''

    try:
        return Markup(
            '<a href="%s">%s</a>'
            % (
                url_for(
                    # Flask-Admin creates URL's namespaced w/ model class name, lowercase.
                    '%s.details_view' % rel_model.__class__.__name__.lower(),
                    id=rel_model.id,
                ),
                rel_model,
            )
        )
    except werkzeug.routing.BuildError as e:
        return Markup(
            '<span class="label label-danger">Error</span> <small>%s</small>' % e
        )