Daw*_*son 0 html python django templates
我见过类似的问题和答案,但没有一个能解决我的问题.
我希望我的视图执行用户组检查,然后通过变量将其传递给模板.然后,模板将使用该模板以不同的方式显示不同的用户组.
我的views.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
Run Code Online (Sandbox Code Playgroud)
在我的模板中,我会像这样使用变量:
{% if is_canner %} canner stuff goes here {% endif %}
Run Code Online (Sandbox Code Playgroud)
我不确定如何传递这个变量,我认为它使用上下文来发送它像这样:
return render(request, 'cans/cans.html', context({"is_canner": is_canner}))
Run Code Online (Sandbox Code Playgroud)
但这给了我错误 - 上下文不可调用.
context不是一个函数,它是render函数的一个参数,例如
context = {"is_canner": is_canner}
return render(request, 'cans/cans.html', context)
Run Code Online (Sandbox Code Playgroud)
docs:https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render
更多背景信息:Django - render(),render_to_response()和direct_to_template()之间有什么区别?