我正在创建基于web的系统,其中我有5到6个不同的角色和访问类型。我研究了如何实现这一点,只有在django admin中创建组并将用户分配到其中时,才能完成所有工作,但只能从管理部分开始。我需要从视图中创建这个。我已经有了一个表单,可以通过电子邮件和下拉菜单添加用户来设置角色类型。
任何建议都将不胜感激,因为到目前为止,如果不从django管理员分配用户,我不知道如何实现这一点。
my model.py for users:
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
ADMIN = 1
RECEPTION = 2
HEADOFDEPARTMENT = 3
EMPLOYEE = 4
PATIENT = 5
NOTACTIVE = 6
ROLE_CHOICES = (
(ADMIN, 'Admin'),
(RECEPTION, 'Reception'),
(HEADOFDEPARTMENT, 'HeadOfDepartment'),
(EMPLOYEE, 'Employee'),
(PATIENT, 'Patient'),
(NOTACTIVE, 'NotActive'),
)
role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=True, null=True)
#email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, blank=True, default='')
is_superuser = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True)
is_employee = models.BooleanField(default=True)
is_headofdepartment = models.BooleanField(default=True)
is_reception = models.BooleanField(default=True)
is_patient = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
像这个
from django.contrib.auth.models import Group
def ViewFunc(request):
... #your func
role = Group.objects.get(name='role')
role.user_set.add(user)
您可以在视图中以所需的方式检索用户对象,然后将其添加到组中的用户集中,完成。
编辑将用户Foo
添加到Admins
组。
from django.contrib.auth.models import Group, User
def ViewFunc(request):
user = User.objects.get(username = 'Foo')
role = Group.objects.get(name='Admins')
role.user_set.add(user)