众所周知,django提供了强大的用户和身份验证应用程序。
通常,有两种方法可以自定义用户
使用OneToOneField方式。我们可以定义一个保留一些用户信息字段的模型配置文件。我们也可以使用get_profile方法来获取配置文件。但是,有一个问题,如果 我们得到用户配置文件,我们必须加入数据表。一些代码演示:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User)
使用AbstractBaseUser,PermissionsMixin。我们可以通过更改django - 1.5中的AbstractBaseUser,PermissionsMixin来定制用户,并且必须定义UserAdmin.the文档:https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#extending-the-existing-user-model
我很困惑,不知道哪条路更好?
答案 0 :(得分:0)
现在最好的方法就是这样做,因为Django 1.5使用custom user models,将AUTH_USER_MODEL
设置为您的用户模型。
答案 1 :(得分:0)
没有理由感到困惑。您链接到的文档是正确的:您应该扩展AbstractBaseUser。
此外,您应该升级到1.6版。
答案 2 :(得分:0)
您需要做的是将AUTH_USER_MODEL
添加到具有自定义用户类路径的设置,该用户类扩展了AbstractBaseUser(更可自定义的版本)或AbstractUser。
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=MyUserManager.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, date_of_birth, password): """ Creates and saves a superuser with the given email, date of birth and password. """ u = self.create_user(username, password=password, date_of_birth=date_of_birth ) u.is_admin = True u.save(using=self._db) return u class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255 ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their email address return self.email def __unicode__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin