Django模板中的列表未按预期工作

2024-03-29 09:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如果在配置文件视图中循环浏览我的用户组以插入页面的不同块,但由于某些原因,它们并不像我期望的那样相等。模板如下:

{{ user_groups }}

{% for g in user_groups %}
    {{ g }}
    {% if g == "client" %}
        client things
    {% endif %}

    {% if g == "guardian" %}
        guardian things
    {% endif %}

{% endfor %}

{% for group in request.user.groups.all %}
    {{ group }}
    {% ifequal group "guardian" %}
        this is a guardian
    {% endifequal %}
{% endfor %}

{% if "guardian" in user_groups %}
     Give me some guardian stuff
{% endif %}

输出:
[<;Group:guardian>;]监护人监护人


如您所见,我对实际用户对象和传递到context[]中的列表都做了此操作。在这两种情况下,列表本身没有迭代问题。两个循环都显示原始变量输出,但equals操作失败。你知道吗

我可以让它做一些比较,比如{% ifequal "something" "something" %},它会显示if块中的内容,但是将列表元素与字符串进行比较似乎没有任何效果。你知道吗

我知道我不能在if块中声明列表,但我决不能这样做。你有没有想过为什么会失败?我错过了什么小事吗?你知道吗


Tags: inclient列表forifgroupsomethinggroups
1条回答
网友
1楼 · 发布于 2024-03-29 09:24:55

使用{{ group }}隐式地将group对象转换为字符串,调用__unicode____str__方法(取决于python版本)。对于用户组,这很可能返回一个包含值group.name的字符串。你知道吗

但是,这种隐式转换不会发生在if语句中(也不应该发生)。因此,字符串"guardian"永远不能等于组对象guardian。你知道吗

我建议将此逻辑放到视图中,而不是模板中,这样可以使用更多函数并进行实际筛选:

def myview(request):
    context['is_guardian'] = request.user.groups.filter(name='guardian').exists()
    context['is_client'] = request.user.groups.filter(name='client').exists()
    return render(request, 'my_template.html', context)

以及您的模板:

{% if is_guardian %}
    ...
{% endif %}

相关问题 更多 >