【发布时间】:2015-02-19 20:57:26
【问题描述】:
情况
我正在创建一个允许创建用户的简单端点。我需要一个不在我的用户模型中的字段(即confirm_password)。我将运行验证,比较这个字段和我模型中的另一个字段,然后在序列化程序中不再使用附加字段。
问题
DRF 版本 3 改变了实现这一点的过程,我不太明白文档建议我做什么。有关文档,请参阅 here。
尝试解决方案
我创建了一个UserSerializer,看起来像这样:
from django.contrib.auth import get_user_model
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
confirm_password = serializers.CharField(allow_blank=False)
def validate(self, data):
"""
Checks to be sure that the received password and confirm_password
fields are exactly the same
"""
if data['password'] != data.pop('confirm_password'):
raise serializers.ValidationError("Passwords do not match")
return data
def create(self, validated_data):
"""
Creates the user if validation succeeds
"""
password = validated_data.pop('password', None)
user = self.Meta.model(**validated_data)
user.set_password(password)
user.save()
return user
class Meta:
# returns the proper auth model
model = get_user_model()
# fields that will be deserialized
fields = ['password', 'confirm_password',
'username', 'first_name', 'last_name', 'email']
# fields that will be serialized only
read_only_fields = ['is_staff', 'is_superuser']
# fields that will be deserialized only
write_only_fields = ['password' 'confirm_password']
我希望在validate 中弹出confirm_password 可以解决我的问题,但我得到以下信息:
在序列化程序
UserSerializer上尝试获取字段confirm_password的值时得到KeyError。序列化器字段可能命名不正确,并且与OrderedDict实例上的任何属性或键都不匹配
【问题讨论】:
-
提醒一下,对于大多数人来说,将
Meta类放在序列化程序的顶部是很常见的,因为它包含您通常要查找的大部分信息。 -
啊,这很有道理。我很感激!
标签: python django django-rest-framework