gpt4 book ai didi

authentication - 使用 django allauth 注册自定义用户

转载 作者:行者123 更新时间:2023-12-04 06:38:10 24 4
gpt4 key购买 nike

我有一个自定义用户模型:

class User(AbstractUser):
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=False) # validators should be a list
email = models.EmailField(blank=False, null=False)
points = models.PositiveIntegerField(default=0)

REQUIRED_FIELDS = ['phone_number', 'email']

objects = UserManager()

使用他的 UserManager:

class UserManager(BaseUserManager):
def create_user(self, username, email, phone_number, password):
if not username:
raise ValueError('Users must have a username')
if not email:
raise ValueError('Users must have an email address')
if not phone_number:
raise ValueError('Users must have a phone_number')

user = self.model(
username,
phone_number,
email=self.normalize_email(email)
)

user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, username, email, phone_number, password):
if not username:
raise ValueError('Users must have a username')
if not email:
raise ValueError('Users must have an email address')
if not phone_number:
raise ValueError('Users must have a phone_number')

user = self.create_user(
username,
phone_number,
email=self.normalize_email(email)
)

user.set_password(password)
user.is_superuser = True
user.save(using=self._db)
return user

我正在使用 allauth 来注册用户,但是当我在/rest-auth/registration (POST) 中注册一个新用户时,这些字段仍然是默认的(用户名、电子邮件、密码 1、密码 2),而不是例如添加电话号码。如何允许更多(或删除一些)字段来注册新用户?

=== 编辑 ===

我也有在我的 settings.py

AUTH_USER_MODEL = 'userTest.User'
ACCOUNT_SIGNUP_FORM_CLASS = 'userTest.forms.RegisterForm'

在 forms.py 中,一个仅用于测试的表单,但它似乎不起作用:

class RegisterForm(forms.Form):
phone_number = forms.CharField(label='Phone Number', max_length=17)
first_name = forms.CharField()

def signup(self, request, user):
user.phone_number = self.cleaned_data['phone_number']
user.first_name = self.cleaned_data['first_name']
user.save()

最佳答案

你必须扩展 AbstaractBaseUser

from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager)

class User(AbstractBaseUser):
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=False) # validators should be a list
email = models.EmailField(blank=False, null=False)
points = models.PositiveIntegerField(default=0)

REQUIRED_FIELDS = ['phone_number', 'email']

objects = UserManager()

关于authentication - 使用 django allauth 注册自定义用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49226024/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com