【发布时间】:2020-05-30 09:10:34
【问题描述】:
我应该使用 is_valid() 函数在 drf 的 put() 函数中验证我的用户数据吗? 因为当我使用它时,is_valid.errors 表示具有此用户名和电子邮件的模型已经存在!我无法理解错误的含义,因为我认为应该在我想要更新之前保存一些东西
序列化器.py
class UserCreateSerializers(ModelSerializer):
class Meta:
model = User
fields = ('name','email','family',"username","password","profile_pic")
def update(self, instance, validated_data):
print("from update try")
#more dry
for i in validated_data.keys():
if hasattr(instance,str(i)) and str(i) !="password":
setattr(instance,str(i),validated_data.get(str(i)))
elif hasattr(instance,str(i)) and str(i) =="password":
instance.set_password(validated_data.get('password'))
setattr(instance,"username",validated_data.get('new_username'))
instance.save()
views.py
def put(self,request):
username = request.data['username']
user = User.objects.get(username = username)
serialized = UserCreateSerializers(data = request.data)
if serialized.is_valid():
serialized.update(user,serialized.validated_data)
return Response(data ={"status":"api_user_update_ok"} , status = status.HTTP_201_CREATED)
else:
print(serialized.errors)
return Response(data = {"status":"api_user_update_failed","error":serialized.errors.get('email')[0]},status = status.HTTP_400_BAD_REQUEST)
使用 put 方法的客户端数据:
name:user
family:useri
username:user2
password:1234
new_username:user22
email:user@gmail.com
错误是:
{'email': [ErrorDetail(string='使用此电子邮件的用户已经存在。', code='unique')], 'username': [ErrorDetail(string='user with this 用户名已经存在。', code='unique')]} 错误请求: /api/v0/registration/signup
服务器响应是:
{
"status": "api_user_update_failed",
"error": "user with this email already exists."
}
感谢您的帮助。
【问题讨论】:
标签: django django-rest-framework