gpt4 book ai didi

django - 用户名在 Django 自定义模型中保存为空

转载 作者:行者123 更新时间:2023-12-04 07:25:09 24 4
gpt4 key购买 nike

当我从 postman 发送帖子请求以注册新用户时,用户名保存为空白/破折号。
为什么用户名保存为空白我不明白。
但是当我从 django admin 添加时,它会正确保存。
这是 postman 图片
postman post request image
这是结果
django result after sending post request
自定义客户经理

class CustomAccountManager(BaseUserManager):
def create_superuser(self, email, username, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_active', True)
other_fields.setdefault('is_admin', True)
other_fields.setdefault('is_superuser', True)
if other_fields.get('is_staff') is not True:
raise ValueError(
'Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError(
'Superuser must be assigned to is_superuser=True.')
return self.create_user(email, username, password, **other_fields)

def create_user(self, email, username, password, **other_fields):
if not email:
raise ValueError(_('You must provide an email address'))
if not username:
raise ValueError(_('You must provide an username'))
if " " in username:
raise ValueError(_('Username should not contain space'))
email = self.normalize_email(email)
user = self.model(email=email, username=username, **other_fields)
user.set_password(password)
user.save()
return user

自定义用户模型

class NewUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True, null=False, blank=False)
username = models.CharField(max_length=150, unique=True, null=True)
first_name = models.CharField(max_length=150, blank=True)
objects = CustomAccountManager()
# more
class Meta:
verbose_name = 'NewUser'

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']

def __str__(self):
return str(self.username)

模型序列化器
class RegisterNewUserSerializer(serializers.ModelSerializer):
class Meta:
model = NewUser
fields = ('email', 'password', 'username')
extra_kwargs={'password':{'write_only':True}}
def validate(self, data):
if hasattr(self, 'initial_data'):
unknown_keys = set(self.initial_data.keys()) - set(self.fields.keys())
if unknown_keys:
raise ValidationError("Got unknown fields: {}".format(unknown_keys))
return data
def validate_username(self, value):
if " " in value:
raise serializers.ValidationError("Username should not contain space")

def save(self):
newuser = NewUser(email = self.validated_data['email'],
username = self.validated_data['username']
)
password = self.validated_data['password']

newuser.set_password(password)
newuser.save()
return newuser
发布请求
class RegistrationView(APIView):
permission_classes = [ AllowAny ]
def post(self, request):
reg_serializer = RegisterNewUserSerializer(data = request.data)
print(request.data)
print(reg_serializer)
if reg_serializer.is_valid():
print('lololololololololololo')
reg_serializer.save()
return Response(data=request.data,status=status.HTTP_201_CREATED)
return Response(reg_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

最佳答案

您的验证器应该返回数据,因此:

def validate_username(self, value):
if " " in value:
raise serializers.ValidationError("Username should not contain space")
# ↓ return the value
return value
在 Python 中,函数调用总是会返回一些东西(除非引发异常)。如果没有明确 return语句被触发, None被退回。

关于django - 用户名在 Django 自定义模型中保存为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68246213/

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