How to make active page button highlight in Django

When switching between users, it remained unclear – which user’s data are you currently viewing?
There was a need to designate an active button that corresponds to the user’s page being viewed. This way it will be easy for me to switch between users as a service administrator.

    checked_user = #getting current user id
    userandid = [] #create an enpty list of users
    userslib = User.objects.all()
    if User.objects.filter(pk=checked_user, groups__name='manager').exists():
     for user in userslib:
       userandid.append((, user.username.title())) #if user in group MANAGER - appending list for template buttons
       userandid = [] # if user not in group MANAGER - list still empty
    q = request.GET.get('q')
    if .........:
        if User.objects.filter(pk=checked_user, groups__name='manager').exists():
            username = user_id
            raise Http404
        username =
        user_id =


context = {'user_id': user_id, '...': ...}


See also  Days counting in Django model for graph generation

Then I send the ID of the current user to the template:

{% for item in userandid %}
    {% if item.0 == user_id %}
<form action="{{ item.0 }}">
    <button type="submit" class="btn btn-dark">{{ item.1 }}</button>
    {% else %}
<form action="{{ item.0 }}">
    <button type="submit" class="btn btn-light">{{ item.1 }}</button>
    {% endif %}
{% endfor %}


I generate buttons with a loop. If the user of the button and the user of the page matched, the html block changes.

Author: admin

Leave a Reply

Your email address will not be published. Required fields are marked *