【问题标题】:use django template with dash application将 django 模板与 dash 应用程序一起使用
【发布时间】:2018-07-29 01:45:18
【问题描述】:

我已经设置了一个适用于我的 django 网站的 dash 应用程序,但我希望将 dash 应用程序放在具有模板的页面上。

我的设置是常用的,即:

views.py

def dispatcher(request):
    '''
    Main function
    @param request: Request object
    '''

    params = {
        'data': request.body,
        'method': request.method,
        'content_type': request.content_type
    }
    with server.test_request_context(request.path, **params):
        server.preprocess_request()
        try:
            response = server.full_dispatch_request()
        except Exception as e:
            response = server.make_response(server.handle_exception(e))
        return response.get_data()

@login_required
def dash_index(request, **kwarg):

    return HttpResponse(dispatcher(request))


@csrf_exempt
def dash_ajax(request):
    return HttpResponse(dispatcher(request), content_type='application/json')

urls.py

urlpatterns = [
    re_path('^_dash-', views.dash_ajax),
    re_path('^', views.dash_index),
] 

上面的代码工作正常。 现在,我尝试了以下方法将页面(查看 dash_index)嵌入模板(称为仪表板模板)中。该模板不是用于格式化应用程序本身,而是用于将“围绕”应用程序的元素,例如导航栏、页脚、菜单等。

试试n°1

@login_required
def dash_index(request, **kwarg):

    template_name = "dashboard_template.html"
    return HttpResponse(dispatcher(request),template_name)

不会产生错误,但不会显示模板。

尝试第二个:

@login_required
def dash_index(request, **kwarg):

    template = loader.get_template("dashboard_template.html")
    return HttpResponse(template.render(dispatcher(request)))

我从 urls.py 文件中得到以下错误

AttributeError: module 'app_name.views' has no attribute 'dash_index'

尝试 n°3:

@login_required
def dash_index(request, **kwarg):

    return render(dispatcher(request),"dashboard_template.html")

同样的错误

AttributeError: module 'app_name.views' has no attribute 'dash_index'

有人可以帮忙吗?

【问题讨论】:

    标签: python django templates embed plotly-dash


    【解决方案1】:

    你必须尝试:-

    return render(request, 'dashboard_template.html', context={'dash': dispatcher(request)})
    

    在您的dashboard_template.html 中,确保添加安全。

    {{ dash|safe }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2019-02-01
      相关资源
      最近更新 更多