0

This is what I expect: if a user has position "1" (Admin) the nav menu in home.html must show "Admin" link to an admin page. If a user has position "2" (User) it won't show the link.

But when I run server this code generate as many Admin links as there are registered users. I want only one link for currently logged-in user to be shown. How can I do that? I know that there's something wrong with "for user in position", but how to fix it for currently logged-in user?

models.py

class Profile(models.Model):
    positions = (
        ('1', 'Admin'),
        ('2', 'User'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    position = models.CharField(max_length=50, default='Position', choices=positions)

views.py

def home(request):
    user_position = Profile.objects.all()
    return render(request, 'home.html', {
        'position': user_position,
        })

home.html

{% for user in position %}
    {% if user.position == '1' %}
        <a class="nav-link" aria-current="page" href="/admin">Admin</a>
    {% endif %}
{% endfor %}
mgksmv
  • 5
  • 1
  • 4

1 Answers1

0

You can also use the is_superuser attribute in your template to achieve this:

{% if user.is_superuser %}
 <a href="#">admin</a>
{% endif %}

if you want to check it based on the username only you can use:

{% if user.username == "Admin" %}
   <a href="#">admin</a>
{% endif %}

Another thing you can do is to create 2 groups inside your admin panel; admins & users. Then you have to create a custom template tag(has_group for example) to show the nav items based on these groups which is a better solution i think. Then you can use something like this in your template:

{% if user|has_group:"admin" %} 
    <p>User belongs to the admin group 
{% else %}
    <p>belongs to users group</p>
{% endif %}
barbaart
  • 837
  • 6
  • 14
  • So I don't need to create custom positions (Admin and User)? – mgksmv Mar 10 '21 at 10:11
  • Ok, but how to do the same thing without using user.is_superuser? Can we check if user is "Admin" somehow? I want to create other categories for positions later, so I'm going to need to do it the other way. – mgksmv Mar 10 '21 at 10:46