[Fixed]-Override django model save function that extends AbstractBaseUser

1๐Ÿ‘

โœ…

Add or update in your code

AgentSerializer(serializers.py)

class AgentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Agents

    def create(self, validated_data):
        return Agents.objects.create(**validated_data)

In views.py

class AgentViewSet(viewsets.ModelViewSet):
    queryset = Agents.objects.all()
    serializer_class = AgentSerializer
    permission_classes = (permissions.AllowAny,)
    http_method_names = ['post']

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            Agents.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

        return JSONResponse(serializer.errors, status=400)

In models.py:

class MyUserManager(BaseUserManager):
    def _create_user(self, email, password,
                 is_staff, **extra_fields):
        password= # Generate random password
        email = self.normalize_email(email)
        user = self.model(email=email,
        is_staff=is_staff, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    def create_user(self, email, password=None, **extra_fields):
        return self._create_user(email, password, False
                             **extra_fields)
๐Ÿ‘คDeep 3015

0๐Ÿ‘

Try overriding the create_user method in your MyUserManager. Something like:

def create_user(self, **kwargs):
    kwargs['password'] = # Generate random password
    return super().create_user(**kwargs)
๐Ÿ‘คlucasnadalutti

Leave a comment