Check permission inside a template in Django

前端 未结 4 1391
甜味超标
甜味超标 2020-12-01 08:46

Can I use the Auth application\'s permission checking inside a template in Django? (I want to display a simple form at the end of the template for privileged users)

相关标签:
4条回答
  • 2020-12-01 09:11

    If you are looking to check for permissions in templates, the following code would suffice:

    {% if perms.app_label.can_do_something %}
    <form here>
    {% endif %}
    

    Where model refers to the model that the user need permissions to see the form for.

    Refer to https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions for more examples.

    The currently logged-in user's permissions are stored in the template variable {{ perms }}

    (This requires the following context processor to be enabled: django.contrib.auth.context_processors.auth)

    0 讨论(0)
  • 2020-12-01 09:19

    If you need more granularity in checking perms (on a particular object for example), check out this extension: http://django-authority.readthedocs.org/en/latest/check_templates/

    0 讨论(0)
  • 2020-12-01 09:30

    Tested on Django 2.0 +

    If you want to see all the permissions the logged in user has, on your template (.html), print :

    {{ perms.app_name }}
    

    Or

    {{ perms }}

    In order to check if user has permission , use:

    {% if perms.app_name.change_model_name_lower_cased %}
    

    E.g :

    {% if perms.Utilization.change_invoice %}
    

    Here: Utilization is my App name. Invoice is a model name.

    Note that in general, there will be 4 kinds of permissions:

    • change [E.g Utilization.change_projectemail]
    • view [E.g Utilization.view_invoice]
    • delete [E.g Utilization.delete_invoicetype]
    • add [E.g Utilization.add_invoicetype]

    Also , if you want to see all permissions a user has due to the groups he belongs to, launch Django shell...

    user = User.objects.get(username='somename')
    user.get_group_permissions()
    

    Here, all permissions listed, are due to the groups he belongs to.

    0 讨论(0)
  • 2020-12-01 09:30

    sorry to 'unearth' this post but I have a problem related to permissions see my post: Django: logic not well applied in template using permissions (perm

    as Arindam seams to be very confortable with this concept I hope he or other could help me

    perms are not apply even if value are correct when I look for {{ perms }} in my template it return an object but not the list of permissions if I look for {{ perms.randomization.can_randomize }} it return False (or True) that is the good value my app is named randomization and I define can_randomize permission in Randomisation models (using meta) that is part of my randomization app

    I check settings.py but all seams to be ok

    0 讨论(0)
提交回复
热议问题