How to separate menu between ordinary and privileged users in Django

If you want to display a list of links to user profiles. To do this, you need to extract data from the model and pass it to the template.

But you need to do this in such a way that a user who is not a member of the manager group does not receive this data. Let’s do a group membership check and build a list of usernames and their IDs.

from django.contrib.auth.models import User, Group
#########################################
    checked_user = request.user.id
    userandid = []
    userslib = User.objects.all()
    if User.objects.filter(pk=checked_user, groups__name='manager').exists():
        for user in userslib:
            userandid.append((user.id, user.username.title()))

Then we will pass this array to the template and display links through if:

{% for item in userandid %}
<form action="https://reports.evgdev.com/showinfo/{{ item.0 }}">
    <button type="submit" class="btn btn-light">{{ item.1 }}</button>
</form>
{% endfor %}

Results for comparison:

See also  How to generate xlsx file from Django model

Author: admin

Leave a Reply

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