【问题标题】:Passing variables to templates in Django将变量传递给 Django 中的模板
【发布时间】:2014-11-30 10:51:30
【问题描述】:

我见过类似的问题和答案,但没有一个能解决我的问题。

我希望我的视图执行用户组检查,然后通过变量将其传递给模板。然后,模板将使用它在不同的用户组中以不同的方式显示。

我的意见.py:

def cans(request):
    is_canner = request.user.groups.filter(name='canner') #check if user group = canner
    can_list = Can.objects.order_by('name')
    context = {'can_list': can_list}
    return render(request, 'cans/cans.html', context) #need to return is_canner variable here

在我的模板中,我会像这样使用变量:

{% if is_canner %} canner stuff goes here {% endif %}

我不确定如何传递这个变量,我认为它使用上下文来发送它:

return render(request, 'cans/cans.html', context({"is_canner": is_canner}))

但这给了我错误 - 上下文不可调用。

【问题讨论】:

    标签: python html django templates


    【解决方案1】:

    context 不是函数,它是渲染函数的参数,例如

    context = {"is_canner": is_canner}
    return render(request, 'cans/cans.html', context)
    

    文档:https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render

    更多背景信息:Django - what is the difference between render(), render_to_response() and direct_to_template()?

    【讨论】:

    • 加载模板时出现错误:render_to_string() got an unexpected keyword argument 'context'
    • 非常感谢,这正是我要找的。​​span>
    猜你喜欢
    • 2019-04-03
    • 2020-01-06
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 2018-12-03
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多