I는 사용자의 창조를 위해 할 수있는 간단한 엔드 포인트를 작성하고 있습니다. 내 사용자 모델에없는 입력란 (예 : confirm_password
)이 필요합니다. 이 필드와 내 모델에있는 다른 필드를 비교하는 유효성 검사를 실행 한 다음 serializer에서 추가 필드를 사용하지 마십시오.
문제
DRF 버전 3이를 달성하기위한 프로세스를 변경, 나는 꽤 문서 내가 할 제안 무엇인지 이해하지 않습니다. 설명서는 here을 참조하십시오. 나는이처럼 보이는 UserSerializer
을 만든
솔루션에서
시도 : 나는 validate
에 confirm_password
터지는 것은 내 문제를 돌봐하지만, 난 그냥 얻을 것이라고 기대했다
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']
다음 :
Got
KeyError
serializer의confirm_password
필드 값은UserSerializer
입니다. 나는 당신의 비밀번호 확인을 표시하지 않습니다 있으리라 믿고있어 같이 시리얼 필드는, 당신은 쓰기 전용 필드 찾고있는OrderedDict
예를
그냥 머리까지, 그것은 일반적입니다 serializer 상단에 'Meta'클래스가 있는데, 일반적으로 찾고있는 대부분의 정보가 들어 있기 때문입니다. –
아, 그건 이해가됩니다. 감사합니다! – nmagerko