简体   繁体   中英

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[]. 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.

I know I can't declare the list inside the if block, but in no case am I doing that. 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). In the case of a user group, this will most likely return a string containing the value of group.name .

However, this implicit conversion does not take place in an if statement (and it shouldn't). Thus, the String "guardian" can never be equal to the Group object 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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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