Code: SERILIZERS
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("email", "user_name", "password")
def create(self, validated_data):
return User.objects.create_user(**validated_data)
VIEWS
@api_view(["POST"])
@permission_classes([AllowAny])
def CreateUserView(request):
serializer = RegisterSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
if user:
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
MODELS
class CustomAccountManager(BaseUserManager):
def create_user(self, email, user_name, password, **other_fields):
if not email:
raise ValueError(_("You must provide an email address"))
email = self.normalize_email(email)
user = self.model(email=email, user_name=user_name, **other_fields)
user.set_password(password)
user.save()
return user
After i post user i got response data with password.
{
"email": "[email protected]",
"user_name": "sdwxcvgfsdefsdf",
"password": "pbkdf2_sha256$320000$g74DLAMRDypcK6LuGriBio$
}
How can i remove that password from returned data?
CodePudding user response:
Into serializer
fields = ("email", "user_name",)
extra_kwargs = {'password': {'write_only': True}}
Actually delete password field from it
CodePudding user response:
According to docs, you can use extra_kwargs. So your serializer would look like -
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("email", "user_name", "password")
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
return User.objects.create_user(**validated_data)