5

我创建了一个用户应用程序MyUser,它是AbstractBaseUser. 我的印象是该模型MyUser将取代标准Auth.User,只要它在settings.py

AUTH_PROFILE_MODULE = 'profile.MyUser'

我现在的问题是我无法为在 MyUser 模型中注册的用户设置权限。当我尝试设置组成员资格和权限时,出现错误User' instance expected, got <MyUser: username>

如何将我的用户模型的用户添加到权限和正确的组?

class MyUserManager(BaseUserManager):
    def create_user(self, username, email, phone, password=None, company=False):
        if not email:
            raise ValueError('Users must have an email address')
        if not username: username = email.split('@')[0]
        user = self.model(
            email=MyUserManager.normalize_email(email),
            username=username,phone=phone,)
        user.set_password(password)
        user.save(using=self._db)

        # add to user group and set permissions
        if company: 
            g = Group.objects.get(name='company')
            p = Permission.objects.get(codename='add_company')
        else: 
            g = Group.objects.get(name='user')
            p = Permission.objects.get(codename='add_user')
        g.user_set.add(user)
        user.user_permissions.add(p)
        return user

class MyUser(AbstractBaseUser):
    username = models.CharField(max_length=254, unique=True, blank=True, null=True)
    email = models.EmailField(max_length=254, unique=True, db_index=True)
    phone = models.CharField(_('Phone Number'), max_length=25, blank=True, null=True,)

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['phone']

    objects = MyUserManager()

    def get_full_name(self):
        return self.email
    ...
4

2 回答 2

8

只需添加PermissionsMixin到您的模型声明中!:)

class MyUser(AbstractBaseUser, PermissionsMixin):
    ...

这是 Django 文档的相关部分

于 2013-05-02T23:20:47.493 回答
2

您可能已经解决了您的问题,但为了完整起见,您的意思是在 Django 1.5 中创建自定义用户模型时参考设置 AUTH_USER_MODEL 与 AUTH_PROFILE_MODULE。

参考:https ://docs.djangoproject.com/en/1.5/topics/auth/customizing/#substituting-a-custom-user-model

于 2013-11-05T15:15:29.073 回答