DRF serializer do not return a value with extra_kwargs of write_only


Keywords:django 


Question: 

I'm practicaly copying the exemple code from the documentation, but the password field, with "extra_kwargs = {'password': {'write_only': True}}" is not returned as validated data.

this is the code:

class UserProfileSerializer(serializers.ModelSerializer):

class Meta:
    model = models.UserProfile
    fields = ('email', 'first_name', 'last_name', 'birthday', 'gender', 'telephone', 'password')
    extra_kwargs = {'password': {'write_only': True}}

def create(self, validated_data):
    user = models.UserProfile(
        email=validated_data['email'],
        first_name=validated_data['first_name'],
        last_name=validated_data['last_name'],
        birthday=validated_data['birthday'],
        gender=validated_data['gender'],
        telephone=validated_data['telephone']
    )

    user.set_password(validated_data['password'])
    user.save()

    return user

Take a look at the local variables. "password" is passed to the initialization function but do not return as validated_data

self:

UserProfileSerializer(data={'email': 'magalhaes@magalhaes.com', 'first_name': 'eduardo', 'last_name': 'magal', 'birthday': None, 'gender': None, 'telephone': '123465', **'password': 123456**}):
    email = EmailField(max_length=255, validators=[<UniqueValidator(queryset=UserProfile.objects.all())>])
    first_name = CharField(max_length=64)
    last_name = CharField(max_length=64)
    birthday = DateField(allow_null=True, required=False)
    gender = ChoiceField(allow_null=True, choices=(('M', 'Male'), ('F', 'Female'), ('O', 'Outro')), required=False)
    telephone = CharField(allow_null=True, max_length=50, required=False)
    password = CharField(max_length=128, write_only=True)

validated_data:

{'birthday': None,
 'email': 'magalhaes@magalhaes.com',
 'first_name': 'eduardo',
 'gender': None,
 'last_name': 'magal',
 'telephone': '123465'}  **No password...**

Thanks in advance!!


2 Answers: 

user_serializer = UserProfileSerializer(data=request.data)
if user_serializer.is_valid():
   user_serializer.save()
else:
   print(user_serializer.errors)

then you will know why you password is not vaild.



def your_view(request):
    if request.method == 'POST':
        serializer = UserProfileSerializer(request.data)
        return Response(serializer.data)
    else:
        do something else


and your request payload would be like this,

{
    "email": "my email",
    "first_name": "my name",
    "last_name": "my last name",
    "birthday": "DOB",
    "gender": "M",
    "telephone": "9999111133",
    "password": "my secret"
}