स्थितिDjango में अतिरिक्त Serializer फील्ड्स बाकी फ्रेमवर्क 3
मैं एक साधारण endpoint है कि एक उपयोगकर्ता के निर्माण के लिए अनुमति देता है बनाने रहा हूँ। मुझे ऐसे क्षेत्र की आवश्यकता है जो मेरे उपयोगकर्ता मॉडल में नहीं है (यानी, confirm_password
)। मैं सत्यापन को चलाऊंगा जो इस क्षेत्र और मेरे मॉडल में मौजूद किसी अन्य फ़ील्ड की तुलना करता है, और फिर धारावाहिक में फिर से अतिरिक्त फ़ील्ड का उपयोग न करें।
समस्या
डीआरएफ संस्करण 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
पॉपिंग अपनी समस्याओं का ख्याल रखना होगा, लेकिन मैं तो बस मिल निम्नलिखित:
KeyError
मिला जब एक प्राप्त करने का प्रयास किया गया serializerUserSerializer
पर फ़ील्डconfirm_password
के लिए मान। serializer क्षेत्र गलत तरीके से और न नाम दिया जा सकताOrderedDict
उदाहरण
बस एक सिर ऊपर है, यह आम है कि ज्यादातर लोगों को डाल करने के लिए के लिए धारावाहिक के शीर्ष पर 'मेटा' वर्ग, क्योंकि इसमें अधिकतर जानकारी शामिल है जिसे आप आम तौर पर ढूंढ रहे हैं। –
आह, यह समझ में आता है। मैं इसकी सराहना करता हूं! – nmagerko