首頁  >  文章  >  後端開發  >  Django使用者認證系統(三)群組與權限

Django使用者認證系統(三)群組與權限

黄舟
黄舟原創
2016-12-23 17:42:551327瀏覽

Django的權限系統很簡單,它可以賦予users或groups中的users權限。

Django admin後台就使用了該權限系統,不過也可以用到你自己的程式碼中。

User物件有兩個ManyToManyField字段,groups和user_permissions

   groups = models.ManyToManyField(Group, ver  name=_('Trs'),
user> s  片to. A user will '
                               'get all permissions granted to each of '? 'their groups.'),
       related_name="user_set", related_query_name="user")
   user_permissions = models.ManyToManyField(Permission,username permissions = models.ManyToManyField(Permission,username_Permissions = name= ) permissions'), blank=True,
       help_text=_('Specific permissions for this user.'),
       related_name="user_set", related_djryname="şoango", relateds"

myuser.groups = [group_list]
myuser.groups.add(group, group, ...)

myuser.groups.remove(group, group, ...)

myuser.groups.clear()

myuser. user_permissions = [permission_list]

myuser.user_permissions.add(permission, permission, ...)
myuser.user_permissions.remove(permission, permission, ...)
myuser.user_permissions..權限是作為一個Model存在的,建立一個權限就是建立一個Permission Model的實例。

@python_2_unicode_compatible
class Permission(models.Model):
   """
   The permissions system PRovides a way to assign permissions to specus 🜎 The permission system is used by the Django admin site, but may also be
   useful in your own code. The Django admin site uses permissions as follows:

       - The "add" permission

       - The "add" permission

       - The "add" permission

及an object.

       - The "change" permission limits a user's ability to view the change
         list, view the "change" form and change an object.
       - The "delete permission mission 錯誤       - The "delete permission mission mis值set globally per type of object, not per specific object
   instance. It is possible to say "Mary may change news stories," but it's
   not currently possible to say "Mary may change news stories, but only the
   ones she created herself" or "Mary may only change news stories。 CharField(_('name '), max_length=255)
   content_type = models.ForeignKey(ContentType)
   codename = models.CharField(_('codename'), max_length=100)
Managermis
       verbose_name = _( 'permission')
       verbose_name_plural = _('permissions')
       unique_together = (('content_type', 'codename'),) __% _p                   'codename')

   def __str__( 。           six.text_type(self.name))

   def natural_key(self):
       return (self.codename,) + self.content_type.natural_key()
   natural_key.dependencies = ['contenttypes。 50個字元或更少,例如,’Can Vote‘

content_type:必需,一個對於django_content_type資料庫table的引用,table中含有每個應用中的Model的記錄。

codename:必需,100個字元或更少,例如,'can_vote'。

如果要為某個Model建立權限:

from django.db import models

class Vote(models.Model):
  ...
   class Mmiscan:"mis misd "),)


如果這個Model在應用foo中,則權限表示為'foo.can_vote',檢查某個使用者是否具有權限myuser.has_perm('foo.can_vote')

預設權限如果已經在INSTALLED_APPS配置了django.contrib.auth,它會保證為installed applications中的每個Django Model建立3個缺省權限:add, change 和delete。

這些權限會在你第一次執行 manage.py migrate(1.7之前為syncdb) 時建立。當時所有的models都會建立權限。在這之後創建的新models會在再次運行 manage.py migrate時創建這些預設權限。這些權限與admin管理介面中的創建,刪除,修改行為是一一對應的。

假設你有一個應用foo ,其中有一個模型Bar, 你可以用下述方法來測試基本權限:

add: user.has_perm('foo.add_bar')

change: user.has_perm('foo. change_bar')

delete: user.has_perm('foo.delete_bar')

權限模型( Permission model)一般不直接使用。


組Groups

組也存在的Model:

@python_2_unicode_compatible

class Group(models.Model):

   """

  geneat​​ion

   """。   some other label, to those users. A user can belong to any number of
   groups.

   A user in a group automatically has all the permissions granted to that
group mis at the mission  orat, coo​​nectronw mis​​nable Smission Smis​​ity, 錯誤edit_home_page, any user in that group will have that permission.

   Beyond permissions, groups are a convenient way to categorize users to
   apply some label, or extended functionals function functionalh. and you could write code that would
   do special things to those users -- such as giving them access to a
   members-only portion of your site, or sending them s-only email   name = models.CharField(_ ('name'), max_length=80, unique=True)
   permissions = models.ManyToManyField(Permission,
       verbose_name=_('permissions'),      verbose_name=_('permissions'),    .
   class Meta:
verbose_name = _('group')
       verbose_name_plural = _('groups')

   def __str__(self):
selfself :        return (self.name,)


字段fields:

name:必需,80個字元或更少,例如, 'Awesome Users'。

permissions:ManyToManyField to Permission

permissions:ManyToManyField to Permission

group.permissions = [permission_list]
group.permissions.add(permission, permission, ...)
group.permission.removemission. .clear()


Programmatically creating permissions

除了可以使用Model meta來建立權限,也可以直接用程式碼建立。

例如,為myapp應用中的BlogPost模型建立一個can_publish權限:

from myapp.models import BlogPost

from django.contrib.auth.models import Group, Permission

from django.contrib.auth.models importb. content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.create(codename='can_publish',
         Can Publish Posts',
                                      content_type=content_type)

時賦予一個物件它的user_permissions屬性或賦予一個Group通過它的permissions屬性。

權限快取

User的權限檢查時是可以被快取的,如果一個新權限被賦予一個User,如果再立即檢查是不會被檢查出來的。最簡單的方法是重新fetch User物件。

from django.contrib.auth.models import Permission, User
from django.shortcuts import get_object_or_404

def user_gains_perms(request, user_id):user_obpid   #權限檢查會快取現在的權限集合
   user.has_perm('myapp.change_bar')

   permission = Permission.objects.get(codename='change_bar')
   user.user_permissions.user(permission) 緩存has_perm(' myapp.變bar')  # 真

   . ..


權限裝飾器

permission_required(perm[, login_url=None, raise_exception=False])

檢查使用者是否具有某個權限,類似於@login_required()

檢查使用者是否具有某個權限,類似於@login_required()
. import permission_required

@permission_required('polls.can_vote', login_url='/loginpage/')

def my_view(request):

   

在模板中的權限

. { perms }}中,是django.contrib.auth.context_processors.PermWrapper實例。


{{ perms.foo }}


上面的單一屬性是User.has_module_perms的代理。如果user擁有foo中的任一權限,則為True

{{ perms.foo.can_vote }}

上面的兩層屬性查詢是User.has_perm的代理,如果用戶擁有foo.can_vote權限則為True 。

例如:

{% if perms.foo %}

   

You have permission to do something in the foo app.

  com{% if perms.foo.can permp. vote!

   {% endif %}
   {% if perms.foo.can_drive %}

       

You can drive!

   {% endif %}

{% else %}

   

You don't have permission to do anything in the foo app.

{% endif %}



或:

{% if 'foo' in perms %}
 
{% if 'foo' in perms %}
   % if  ' in perms %}
       

In lookup works, too.


   {% endif %}

中文網(www.php.cn)!



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn