我正在使用Django 1.9。當我嘗試將PermissionRequiredMixin添加到基於類的視圖時,它似乎不像預期的那樣工作。我在auth_group中創建了一個新用戶。此auth_group沒有任何應用程序或模型的權限。這個新用戶不是超級用戶或管理員用戶。但該應用程序不會阻止此用戶訪問需要permission_required的特定視圖。Django - PermissionRequiredMixin與自定義用戶模型以及AUTHENTICATION_BACKENDS
首先,這裏是我試圖以確保用戶沒有權限:
user.get_all_permissions() # return set() - empty permission, which is correct.
user.is_superuser # return false, which is correct.
user.has_perm('myapp.add_something or even any words that make no sense') # always return true, which is very weird.
應用程序有自定義的用戶模型,並且也使用Django的allauth作爲AUTHENTICATION_BACKENDS。我不確定PermissionRequiredMixin是否會檢查user.has_perm()並且它總是返回true,所以這就是爲什麼檢查權限無法按預期工作的原因?
# views.py
class My_View(PermissionRequiredMixin, View):
permission_required = 'polls.can_vote'
def get(self, request, *args, **kwargs):
# do something...
return render(request, "template.html", {})
# models.py - Custom User Model
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
group = models.ManyToManyField(Group, through='UserGroupRelationship')
....
# models.py - many-to-many relationship between user and group
class UserGroupRelationship(models.Model):
user = models.ForeignKey("CustomUser")
user_group = models.ForeignKey(Group)
我也嘗試了舊的方式來檢查urls.py的權限。它不阻止用戶訪問,所以我不認爲這是使用PermissionRequiredMixin的問題。
urlpatterns = patterns('',
(r'^vote/', permission_required('polls.can_vote')(VoteView.as_view())),
)
我也搜索了幾天,感謝上帝,我發現了這一點。我無法相信他們不會在文檔中解釋這一點 – diek