I have a custom user model. I have created an api for user registration. Following is my serializer.
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[
UniqueValidator(queryset=get_user_model().objects.all())
]
)
password = serializers.CharField(min_length=8)
class Meta:
model = get_user_model()
fields = ('email', 'password')
extra_kwargs = {'password': {'write_only': True}, }
def create(self, validated_data):
email = validated_data.pop('email')
password = validated_data.pop('password')
user = get_user_model().objects.create_user(email, password, **validated_data)
return user
Here is my view:
class Registration(generics.CreateAPIView):
serializer_class = UserSerializer
queryset = get_user_model().objects.all()
There are two inputs email
and password
. password
field is given as write_only field. But after creating the user, the api returns the hashed password. How can I prevent the password being returned?
In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
HyperlinkedModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.
validated_data is an OrderedDict and you can see it only after is_valid() and is_valid() == True.
You don't need explicitly declare the field on the serializer if use extra_kwargs
try just this:
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[
UniqueValidator(queryset=get_user_model().objects.all())
]
)
class Meta:
model = get_user_model()
fields = ('email', 'password')
extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With