我在Django上有一个站点,我有自定义的用户模型。在现场,我使用 Django 表单,我可以注册并在登录后注册,它运行良好。然后我开始使用DRF和Django-rest-auth。在设置中为其编写路径后,我编写了一个自定义寄存器序列化程序。
from rest_framework import serializers
from ideas.models import Post, Unit, StatusOfPost
from accounts.models import User
from django.contrib.auth import authenticate
from django.contrib.auth import get_user_model
from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
class RegisterSerializer(serializers.Serializer):
phone_number = serializers.CharField(required=True, write_only=True)
username = serializers.CharField(required=True, write_only=True)
email = serializers.CharField(required=True, write_only=True)
first_name = serializers.CharField(required=True, write_only=True)
last_name = serializers.CharField(required=True, write_only=True)
password1 = serializers.CharField(required=True, write_only=True)
password2 = serializers.CharField(required=True, write_only=True)
def get_cleaned_data(self):
return {
'first_name': self.validated_data.get('first_name', ''),
'last_name': self.validated_data.get('last_name', ''),
'address': self.validated_data.get('address', ''),
'username': self.validated_data.get('username', ''),
'password': self.validated_data.get('password', ''),
'email': self.validated_data.get('email', ''),
'phone_number': self.validated_data.get('phone_number',''),
}
def validate_email(self, email):
email = get_adapter().clean_email(email)
if allauth_settings.UNIQUE_EMAIL:
if email and email_address_exists(email):
raise serializers.ValidationError(
("A user is already registered with this e-mail address."))
return email
def validate_username(self, username):
username = get_adapter().clean_username(username)
return username
def validate_password1(self, password):
return get_adapter().clean_password(password)
def validate(self, data):
if data['password1'] != data['password2']:
raise serializers.ValidationError(
("The two password fields didn't match."))
return data
def save(self, request):
adapter = get_adapter()
user = adapter.new_user(request)
self.cleaned_data = self.get_cleaned_data()
adapter.save_user(request, user, self)
setup_user_email(request, user, [])
user.phone_number = self.cleaned_data.get('phone_number')
user.save()
return user
它也可以工作并创建一个新用户,并返回我一个令牌。我的管理员中有一个新用户。但是,如果我想像这个新用户一样登录我的网站,网站会给我写该用户名或密码无效。我不明白为什么,在我的管理员中我看到这个用户,我知道写一个有效的密码(我尝试创建不同的用户,但结果是一个(
我注意到在我的管理员中,新用户的密码没有像在网站上注册时那样编码。
为了比较:
通过 API 注册后编码密码
!Z2Aw4VpN34JidaSNmODVi5MJKRJHTgx0gfROnylA
在网站上注册后的编码密码:
pbkdf2_sha256$100000$aILnGtv6ClxI$KVg1lwjSKf0REZI/M85i2tN/mTUTLxngNVwo4YaCe08=
如果是这样,这可能是一个问题,而不是如何解决?我不知道。
谢谢大家
在函数get_cleaned_data删除
'password': self.validated_data.get('password', ''),
并插入
'password1': self.validated_data.get('password1', ''),
'password2': self.validated_data.get('password2', ''),
它解决了我的问题