gpt4 book ai didi

django - 如果未明确指定,则为 DRF ModelSerializer 中的 "user with this username already exists"

转载 作者:行者123 更新时间:2023-12-05 01:37:46 27 4
gpt4 key购买 nike

虽然我知道如何解决,但我正在尝试理解为什么会出现此错误。只是想更好地理解 DRF 和 Django。

这种格式的JSON来自FE:

{
"username": "username_here",
"password": "password_here"
}

我的看法是:

class UserSigninTokenAPIView(APIView):
permission_classes = [AllowAny]
serializer_class = UserSigninTokenSerializer

def post(self, request):
data = request.data
serializer = UserSigninTokenSerializer(data=data)
if serializer.is_valid(raise_exception=True):
new_data = serializer.data
return Response(new_data, status=HTTP_200_OK)
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

它使用这个序列化器:

class UserSigninTokenSerializer(ModelSerializer):
username = CharField()

class Meta:
model = USERS
fields = [
'username',
'password',
'id'
]

def validate(self, data):
username = data['username']
password = data['password']
user_qs = USERS.objects.filter(username__iexact=username)
if user_qs.exists() and user_qs.count() == 1:
user_obj = user_qs.first()
password_passes = user_obj.check_password(password)
if password_passes:
"""
A number of checks here I removed to keep this clean,
otherwise would just use /api/token/ to get a token.
I want user checks to pass before issuing a token,
because having the token is what indicates they are
logged in successfully.
"""
token = RefreshToken.for_user(user_obj)
return {
'refresh': str(token),
'access': str(token.access_token)
}
else:
Services.user_attempts(user_obj)
raise ValidationError({'error': '''
The credentials provided are invalid.
<br>Please verify the username and password are correct.
'''})

username = CharField() 对我来说似乎是多余的。 documentation说:

The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.

我将其解释为仅在 class Meta: 中指定 field = [] 就足以反序列化 JSON。

但是,当我删除 username = CharField() 时,我得到:

{
"username": [
"user with this username already exists."
]
}

documentation对于明确的规范说:

You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.

这听起来是可选的,但显然必须指定它。

如果有人不介意解释,我在这里错过了什么?

最佳答案

您正在对您的模型使用 ModelSerializer 并且请求是 POST,难怪您为什么会得到这个。

ModelSerializer 用于为 CRUD 操作提供快速的标准序列化,因此当您的请求是 POST 时,您的序列化程序将假定您正在使用该请求创建一个新用户Users 模型的数据,因此将应用创建验证,并且由于用户名是唯一的...,剩下的就是故事了。

尝试使用基本的序列化器,因为你只想读取数据,这样会更简单

关于django - 如果未明确指定,则为 DRF ModelSerializer 中的 "user with this username already exists",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533893/

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