[Django]-Django custom user model password is not being hashed

20👍

It looks like you created a user in a way that does not use your manager’s create_user method, for example through the Django admin.

If you create a custom user, you need to define a custom model form and model admin that handles the password properly.

Otherwise, passwords will not hashed when a user is created through the Django admin.

The example in docs for creating a custom users shows how to create the model form and model admin.

5👍

I know it’s too late now, but I’ll just post this for future reference.
If you’re creating a new user by calling the save function on its serializer, you’ll need to override the create function of the serializer as shown below, (which is pretty obvious, but I got stuck on it for a little bit….)

class SignUpView(views.APIView):
    authentication_classes = ()
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(
        min_length=6, write_only=True, required=True)

    class Meta:
        model = User
        fields = (
            'id', 'email', 'password', 'is_staff',
            'is_active', 'date_joined')

    def create(self, validated_data):
        return User.objects.create_user(**validated_data)
👤dakaii

2👍

Late answer but anyway, you need to make Custom User Model form too with explicit hashing.
Else just make form inheriting UserCreationForm like:

from .models import MyUser
from django.contrib.auth.forms import UserCreationForm    
class UserForm(UserCreationForm):

    class Meta:
        model = User
        fields = ['email']

0👍

Add this in your UserSerialzer.
Basically you have to override the create method in order to hash the password.

def create(self,validated_data):
        user = User.objects.create(email = validated_data['email'])
        user.set_password(validated_data['password'])
        user.save()
        return user

Leave a comment