Tình hìnhbổ sung Serializer Fields trong Django REST của Khung 3
tôi đang tạo ra một thiết bị đầu cuối đơn giản mà cho phép việc tạo ra một người dùng. Tôi cần một trường không có trong mẫu người dùng của tôi (ví dụ: confirm_password
). Tôi sẽ chạy xác nhận so sánh trường này và một trường khác nằm trong mô hình của tôi, và sau đó không bao giờ sử dụng lại trường bổ sung trong bộ nối tiếp.
Vấn đề
DRF phiên bản 3 đã thay đổi quá trình cho việc này, và tôi không hoàn toàn hiểu những gì các tài liệu được đề nghị tôi làm. Xem here để biết tài liệu.
Nỗ lực tại Giải pháp
tôi đã tạo ra một UserSerializer
trông như thế này:
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']
Tôi đã hy vọng rằng popping confirm_password
trong validate
sẽ chăm sóc của các vấn đề của tôi, nhưng tôi chỉ nhận được như sau:
Có
KeyError
khi cố gắng nhận giá trị cho trườngconfirm_password
trên bộ nối tiếpUserSerializer
. Các lĩnh vực serializer có thể được đặt tên không chính xác và không phù hợp với bất kỳ thuộc tính hoặc phím trênOrderedDict
dụ
Chỉ cần một người đứng đầu lên, nó phổ biến cho hầu hết mọi người để đưa Lớp 'Meta' ở đầu bộ nối tiếp, vì nó chứa phần lớn thông tin bạn thường tìm kiếm. –
Ah, điều đó có ý nghĩa. Tôi đánh giá cao nó! – nmagerko