简体   繁体   English

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

[英]Lists in Django templates not working as expected

If looping through my users' groups in a profile view to insert different chunks of the page, but for some reason they aren't equating like I expect them to. 如果在配置文件视图中循环访问我的用户组以插入页面的不同块,但由于某种原因,它们并不像我期望的那样等同。 Here's the template: 这是模板:

{{ 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 %}

Output: 输出:
[<Group: guardian>] guardian guardian [<团体:监护人>]监护人监护人


As you can see I've done this both with the actual user object and with a list passed into context[]. 正如你所看到的,我已经用实际的用户对象和传递给context []的列表完成了这个。 In both cases the list itself has no issue iterating. 在这两种情况下,列表本身都没有问题迭代。 Both loops show the raw variable output, but the equals operations are failing. 两个循环都显示原始变量输出,但是等于操作失败。

I CAN make it do comparisons like {% ifequal "something" "something" %} which will show me the content inside the if block, but comparing a list element to a string just doesn't seem to be working any way I try to get it done. 我可以让它做比较像{% ifequal "something" "something" %}这将显示if块内的内容,但将列表元素与字符串进行比较似乎没有任何方式我尝试把它做完。

I know I can't declare the list inside the if block, but in no case am I doing that. 我知道我不能在if块中声明列表,但在任何情况下我都不这样做。 Any thoughts on why this would be failing? 有关为什么会失败的任何想法? Did I miss something trivial? 我错过了一些微不足道的事吗?

Using {{ group }} implicitly converts the group object to a string, calling it's __unicode__ or __str__ method (depending on your python version). 使用{{ group }}隐式地将group对象转换为字符串,调用它的__unicode____str__方法(取决于您的python版本)。 In the case of a user group, this will most likely return a string containing the value of group.name . 对于用户组,这很可能会返回包含group.name值的group.name

However, this implicit conversion does not take place in an if statement (and it shouldn't). 但是,这种隐式转换不会发生在if语句中(并且不应该)。 Thus, the String "guardian" can never be equal to the Group object guardian . 因此,字符串"guardian"永远不能等于组对象guardian

I'd recommend to get this logic into your view rather than your template, where you can use more functions and do actual filtering: 我建议将此逻辑放入您的视图而不是模板中,您可以在其中使用更多功能并进行实际过滤:

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)

And your template: 而你的模板:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM