如何在Django的auth_user_groups中添加自定义userinfo表? [英] How to add customize userinfo table to auth_user_groups in django?

查看:38
本文介绍了如何在Django的auth_user_groups中添加自定义userinfo表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户表'UserInfo',并创建了两个组'admin'和'普通用户',并赋予了这些组一些权限.

I have a user table 'UserInfo' and created two groups 'admin' and 'normal users' given some permissions to these groups.

我正在根据用户的类型将用户添加到特定的组,即,如果用户是admin,我将向该用户授予admin的权限.

I am adding the users to a particular group based on the type of the user i.e if user is admin I will give the permissions of the admin to that user.

现在,我要检查特定用户是否具有has_perm,并且还要将该用户添加到表auth_user_group中.我该怎么办?

Now I want to check whether a particular user has_perm or not, and also I want to add the user to the table auth_user_group. How can I do this?

推荐答案

每个用户都有一个 groups ManyToManyManager,该列表将列出他们的组.如果要将用户添加到组,请使用 ManyToManyManager API :

Each user has a groups ManyToManyManager that will list their groups. If you want to add a user to a group, use the ManyToManyManager api:

u = User.objects.get(pk=1)
g = Group.objects.get(name='admin')
u.groups.add(g)
u.save()
u.groups.remove(g)
u.save()

将用户添加到组后,他们将继承该组的所有权限.没有等效的 has_perm 检查用户是否在组中,但是有

Once you add a user to a group, they will inherit all permissions of that group. There is no equivalent of has_perm that checks if a user is in a group or not, but there is user_passes_test which you can use to check if a user passes any condition. It works by calling any function you define with the user object:

from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render

def is_admin(user):
   return user.group_set.filter(name='admin').count()

@user_passes_test(is_admin)
def only_admin(request):
    return render(request, 'sekret.html')

这篇关于如何在Django的auth_user_groups中添加自定义userinfo表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆