Reputation: 4664
I have a template
in django
that shows a link if a user has group name different than patient.
My code is:
{% if user.is_authenticated %}
{% for group in user.groups.all %}
{% if group.name != 'Patient' %}
<li {% if request.get_full_path == modules_url %} class="active" {% else%} class="inactive"{% endif %}>
<a href="{% url 'modules' %}"><b style="color:#ff9904;">Modules</b></a>
</li>
{% endif %}
{% endfor %}
{% endif %}
In case a user is a member of four different groups, the link Modules
is shown 4 times in the template.
Is there any way to show it only once?
Upvotes: 0
Views: 741
Reputation: 4664
I found the solution thanks to here. I used the forloop.counter
variable.
{% if user.is_authenticated %}
{% for group in user.groups.all %}
{% if group.name != 'Patient' %}
{% if forloop.counter < 2 %}
<li {% if request.get_full_path == modules_url %} class="active" {% else%} class="inactive"{% endif %}>
<a href="{% url 'modules' %}"><b style="color:#ff9904;">Modules</b></a>
</li>
{% endif %}
{% endif %}
{% endfor %}
{% endif %}
Upvotes: 0
Reputation: 4194
I think by handle using templatetags should easier.
from django import template
from django.contrib.auth.models import Group
register = template.Library()
@register.filter(name='has_group')
def has_group(user, group_name):
"""
{% if request.user|has_group:'grouName' %}
{# do_stuff #}
{% endif %}
return Boolean (True/False)
"""
group = Group.objects.get(name=group_name)
return group in user.groups.all()
Basicly you can also do with this to get first group:
{% if user.groups.all.0 == 'Patient' %}
...
{% endif %}
Upvotes: 1