我創建了一個用戶應用MyUser
,它是AbstractBaseUser
的擴展。我的印象是,該模型MyUser
將取代標準Auth.User
,只要它是在settings.py
Django 1.5:瞭解AbstractBaseUser和權限
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
...
如何設置用戶組級別?當我用'g.user_set.add(user)'設置它時,我得到'TypeError:'用戶'實例,再次得到'作爲錯誤消息。 –
neurix
2013-05-03 00:22:41
用'user.groups.add(g)'做。 – 2013-05-03 06:34:37