how to mention password field in serializer?

前端 未结 4 1001
忘了有多久
忘了有多久 2020-12-16 08:14

I have a custom user for authentication and want to create a serializer class for it my custom user\'s model is like this :

class User (Abs         


        
4条回答
  •  北海茫月
    2020-12-16 08:33

    to hash password, call:

    make_password(origin_password)
    

    example serializers.py:

    from rest_framework import serializers
    from django.contrib.auth.models import User
    from django.contrib.auth.hashers import make_password
    
    
    class UserSerializer(serializers.HyperlinkedModelSerializer):
    
        password = serializers.CharField(
            write_only=True,
            required=True,
            help_text='Leave empty if no change needed',
            style={'input_type': 'password', 'placeholder': 'Password'}
        )
    
        class Meta:
            model = User
            fields = ('url', 'username', 'email', 'password')
    
        def create(self, validated_data):
            validated_data['password'] = make_password(validated_data.get('password'))
            return super(UserSerializer, self).create(validated_data)
    

提交回复
热议问题