Created
August 7, 2019 17:13
-
-
Save akshar-raaj/5e5ccb530ddf0b35b627e62c8ad26980 to your computer and use it in GitHub Desktop.
UserSerializer with overridden create
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserSerializer(serializers.ModelSerializer): | |
def validate_password(self, value): | |
if value.isalnum(): | |
raise serializers.ValidationError('password must have atleast one special character.') | |
return value | |
def validate(self, data): | |
if data['first_name'] == data['last_name']: | |
raise serializers.ValidationError("first_name and last_name shouldn't be same.") | |
return data | |
def to_internal_value(self, value): | |
value['date_joined'] = parser.parse(value['date_joined']) | |
return super().to_internal_value(value) | |
def create(self, validated_data): | |
return User.objects.create_superuser(**validated_data) | |
class Meta: | |
model = User | |
fields = ('username', 'email', 'first_name', 'last_name', 'password', 'date_joined') | |
extra_kwargs = { | |
'password': {'write_only': True} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment