在Django 1.5中将电子邮件设置为用户名

在Django 1.5中将电子邮件设置为用户名,第1张

在Django 1.5中将电子邮件设置为用户名

AbstractbaseUser
没有电子邮件字段,有
AbstractUser

如果要使用电子邮件作为唯一标识符,则需要从AbstractbaseUser继承子类,并使用定义电子邮件字段

unique=True
并编写其他功能,例如
Manager
模型:

from django.contrib.auth.models import AbstractbaseUser, baseUserManager,    PermissionsMixinfrom django.db import modelsfrom django.utils.translation import ugettext_lazy as _from django.utils import timezonefrom django.utils.http import urlquoteclass CustomUserManager(baseUserManager):    def create_user(self, email, password=None, **extra_fields):        """        Creates and saves a User with the given email and password.        """        now = timezone.now()        if not email: raise ValueError('The given email must be set')        email = CustomUserManager.normalize_email(email)        user = self.model(email=email,    is_staff=False, is_active=True, is_superuser=False,    last_login=now, date_joined=now, **extra_fields)        user.set_password(password)        user.save(using=self._db)        return user    def create_superuser(self, email, password, **extra_fields):        u = self.create_user(email, password, **extra_fields)        u.is_staff = True        u.is_active = True        u.is_superuser = True        u.save(using=self._db)        return uclass User(AbstractbaseUser, PermissionsMixin):    email = models.EmailField(_('email address'), unique=True)    first_name = models.CharField(_('first name'), max_length=30, blank=True)    last_name = models.CharField(_('last name'), max_length=30, blank=True)    is_staff = models.BooleanField(_('staff status'), default=False,        help_text=_('Designates whether the user can log into this admin '         'site.'))    is_active = models.BooleanField(_('active'), default=True,        help_text=_('Designates whether this user should be treated as '         'active. Unselect this instead of deleting accounts.'))    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)    objects = CustomUserManager()    USERNAME_FIELD = 'email'    class meta:        verbose_name = _('user')        verbose_name_plural = _('users')    def get_absolute_url(self):        return "/users/%s/" % urlquote(self.pk)    def get_full_name(self):        """        Returns the first_name plus the last_name, with a space in between.        """        full_name = '%s %s' % (self.first_name, self.last_name)        return full_name.strip()    def get_short_name(self):        "Returns the short name for the user."        return self.first_name    # define here other needed methods    # Look at django.contrib.auth.models.AbstractUser

另外,您可能需要将此用户添加到管理页面。查看UserAdmin并重新定义它以与使用电子邮件字段作为唯一标识符的新用户模型兼容。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5629777.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存