当我尝试删除已从数据库注册的用户时,我得到以下信息: 表“users_user”上的更新或删除违反了表“account_emailaddress”上的外键约束“account_emailaddress_user_id_2c513194_fk_users_user_id” 另外,当我注册用户时,只有电子邮件、用户名和密码会在数据库中注册。
序列化器:
class RegisterSerializer(serializers.Serializer):
password = serializers.CharField(
write_only=True,
required=True,
validators=[validate_password],
)
password2 = serializers.CharField(
write_only=True,
required=True,
)
class Meta:
model = User
fields = [
"first_name",
"last_name",
"location",
"username",
"email",
"password",
"password2",
]
extra_kwargs = {
"first_name": {"required": True},
"last_name": {"required": True},
"location": {"required": False},
}
def validate_username(self, username):
username = get_adapter().clean_username(username)
return username
def validate_email(self, email):
email = get_adapter().clean_email(email)
return email
def validate_password1(self, password):
password = get_adapter().clean_password(password)
return password
def validate(self, data):
if data["password"] != data["password2"]:
raise serializers.ValidationError(
{"password": "Password fields didn't match."}
)
return data
def get_cleaned_data(self):
return User(
username=self.validated_data.get("username", ""),
email=self.validated_data.get("email", ""),
password=self.validated_data.get("password", ""),
first_name=self.validated_data.get("first_name", ""),
last_name=self.validated_data.get("last_name", ""),
location=self.validated_data.get("location", ""),
)
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, commit=False)
if "password1" in self.cleaned_data:
try:
adapter.clean_password(self.cleaned_data["password1"], user=user)
except DjangoValidationError as e:
raise serializers.ValidationError(
{"password": list(e.messages)}
)
# user.is_active = False
user.save()
return user
查看:
class RegisterView(CreateAPIView):
serializer_class = api_settings.REGISTER_SERIALIZER
permission_classes = api_settings.REGISTER_PERMISSION_CLASSES
token_model = TokenModel
throttle_scoop = "dj_rest_auth"
@method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get_response_data(self, user):
if allauth_settings.EMAIL_VERIFICATION == allauth_settings.EmailVerificationMethod.MANDATORY:
return {"detail": _("Verification e-mail sent.")}
if api_settings.USE_JWT:
data = {
'user': user,
'access': self.access_token,
'refresh': self.refresh_token,
}
return api_settings.JWT_SERIALIZER(data, context=self.get_serializer_context()).data
elif api_settings.SESSION_LOGIN:
return {"detail": _("User created. Please login.")}
else:
return api_settings.TOKEN_SERIALIZER(data, context=self.get_serializer_context()).data
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
data = self.get_response_data(user)
if data:
response = Response(
data,
status=status.HTTP_201_CREATED,
headers=headers,
)
else:
response = Response(
status=status.HTTP_204_NO_CONTENT,
headers=headers,
)
return response
def perform_create(self, serializer):
user = serializer.save(self.request)
if allauth_settings.EMAIL_VERIFICATION != allauth_settings.EmailVerificationMethod.MANDATORY:
if api_settings.USE_JWT:
self.access_token, self.refresh_token = jwt_encode(user)
elif not api_settings.SESSION_LOGIN:
api_settings.TOKEN_CREATOR(self.token_model, user, serializer)
complete_signup(
self.request._request,
user,
allauth_settings.EMAIL_VERIFICATION,
None,
)
return user
尝试从数据库中删除用户时遇到的错误是由于外键约束违规造成的。具体来说,
account_emailaddress
表有一个引用 users_user
表的外键。要解决此问题,您需要在删除用户之前或期间处理 account_emailaddress
表中的依赖记录。这通常涉及删除或更新相关记录以确保不违反外键约束。关于仅保存电子邮件、用户名和密码的注册问题,序列化程序中的 save
方法似乎未正确保存其他字段(first_name
、last_name
、location
)。您应该确保在保存之前在用户对象上设置这些字段。调整序列化器中的 save
方法以正确设置这些字段应该可以解决该问题。