欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解python如何在django中為用戶模型添加自定義權(quán)限

 更新時(shí)間:2018年10月15日 08:33:39   作者:代碼日志  
這篇文章主要介紹了python如何在django中為用戶模型添加自定義權(quán)限,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

django自帶的認(rèn)證系統(tǒng)能夠很好的實(shí)現(xiàn)如登錄、登出、創(chuàng)建用戶、創(chuàng)建超級(jí)用戶、修改密碼等復(fù)雜操作,并且實(shí)現(xiàn)了用戶組、組權(quán)限、用戶權(quán)限等復(fù)雜結(jié)構(gòu),使用自帶的認(rèn)證系統(tǒng)就能幫助我們實(shí)現(xiàn)自定義的權(quán)限系統(tǒng)達(dá)到權(quán)限控制的目的。

在django中默認(rèn)情況下,syncdb運(yùn)行時(shí)安裝了django.contrib.auth,它會(huì)為每個(gè)模型創(chuàng)建默認(rèn)權(quán)限,如foo.can_change,foo.can_delete和foo.can_add.要向模型添加自定義權(quán)限,可以添加類Meta:在模型下,并在其中定義權(quán)限,如此處所述

我的問(wèn)題是,如果我要為用戶模型添加自定義權(quán)限,該怎么辦?像foo.can_view.我可以用下面的代碼片段來(lái)實(shí)現(xiàn),

ct = ContentType.objects.get(app_label='auth', model='user')
perm = Permission.objects.create(codename='can_view', name='Can View Users', 
                 content_type=ct)
perm.save()

但是我想要一些可以很好地與syncdb一起玩的東西,例如我的自定義模型下的Meta類.我應(yīng)該在類Meta中有這些:在UserProfile下,因?yàn)檫@是擴(kuò)展用戶模型的方式.但是是否正確的方式呢?不會(huì)把它綁定到UserProfile模型?

你可以這樣做:

在Django應(yīng)用的__init__.py中添加:

from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission

# custom user related permissions
def add_user_permissions(sender, **kwargs):
  ct = ContentType.objects.get(app_label='auth', model='user')
  perm, created = Permission.objects.get_or_create(codename='can_view', name='Can View Users', content_type=ct)
post_syncdb.connect(add_user_permissions, sender=auth_models)

原文地址:http://stackoverflow.com/questions/7724265/how-to-add-custom-permission-to-the-user-model-in-django

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論