Skip to content

Instantly share code, notes, and snippets.

@leafsummer
Last active March 22, 2023 23:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save leafsummer/f4d67b58a4cc77174c31935d7e299c9e to your computer and use it in GitHub Desktop.
Save leafsummer/f4d67b58a4cc77174c31935d7e299c9e to your computer and use it in GitHub Desktop.
integrate django password validators with django rest framework validate_password
import django.contrib.auth.password_validation as validators
from rest_framework import serializers
class RegisterUserSerializer(serializers.ModelSerializer):
password = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = ('id', 'username', 'email, 'password')
def validate_password(self, data):
# validators.validate_password(password=data, user=User)
# return data
# here data has all the fields which have validated values
# so we can create a User instance out of it
user = User(**data)
# get the password from the data
password = data.get('password')
errors = dict()
try:
# validate the password and catch the exception
validators.validate_password(password=password, user=user)
# the exception raised here is different than serializers.ValidationError
except exceptions.ValidationError as e:
errors['password'] = list(e.messages)
if errors:
raise serializers.ValidationError(errors)
return super(RegisterUserSerializer, self).validate(data)
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
user.is_active = False
user.save()
return user
@royemmerich
Copy link

Just what I'm looking for, but can you explain to me when the validate_password method gets called?

@royemmerich
Copy link

@mrcoles
Copy link

mrcoles commented Nov 11, 2019

Did you mean to use object-level validation (validate(self, data)) instead of field-level validation (validate_password(self, value))? https://www.django-rest-framework.org/api-guide/serializers/#object-level-validation

@itwasmattgregg
Copy link

This worked for me changing it to object level validation

@Adegitetaiwo
Copy link

I got an error in line 18, it says
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead.

please how do I make this work?

@ocomsoft
Copy link

@Adegitetaiwo I had the same problem.

I changed line 18 to

user = self.instance

And it worked better for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment