我想在我的应用中消除django auth中用户名的概念。我希望用户的email
取代username
。所以我使用下面的代码扩展了AbstractBaseUser
class AuthUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("Users must have an email address")
user = self.model(email=self.normalize_email(email),)
user.is_active = True
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(email=email, password=password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class AuthUser(AbstractBaseUser, PermissionsMixin):
alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message = "Only alphanumeric characters are allowed")
email = models.EmailField(verbose_name='email address',unique=True, max_length=255)
first_name = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
last_name = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
date_joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True, null=False)
is_staff = models.BooleanField(default=False, null=False)
#custom fields
company_name = models.CharField(max_length=100)
telephone_number = models.CharField(max_length=100)
website_url = models.CharField(max_length=100)
objects = AuthUserManager()
USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['first_name']
def get_full_name(self):
fullname = self.first_name + self.last_name
return fullname
def get_short_name(self):
return self.email
def __unicode__(self):
return self.email
在我的serializers.py中我有这个
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = AuthUser
fields = ('email', 'first_name', 'last_name')
def create(self, validated_data):
user = AuthUser.objects.create(**validated_data)
return user
def update(self, instance, validated_data):
instance.email = validated_data.get('email', instance.email)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.save()
return instance
但是当我尝试注册时,我收到以下错误:
{
"username": [
"This field is required."
]
}
我做错了什么?
答案 0 :(得分:0)
在您的序列化程序中,您需要排除username
字段,因为您继承自AbstractBaseUser
并且您仍然拥有'用户名'字段,请添加此exclude = ('username',)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = AuthUser
fields = ('email', 'first_name', 'last_name')
exclude = ('username',)
def create(self, validated_data):
user = AuthUser.objects.create(**validated_data)
return user