搜尋
首頁後端開發Python教學Django使用者認證系統(三)群組與權限

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
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器