How to create a new user with django rest framework and custom user model How to create a new user with django rest framework and custom user model django django

How to create a new user with django rest framework and custom user model


I think one password field is enough. If you want to check the user's twice password input is same, do it in the front-end. You can override a create method from serializer like following.

from rest_framework import serializersclass UserSerializer(serializers.ModelSerializer):    password = serializers.CharField(write_only=True)    class Meta:        model = User        fields = ('first_name', 'last_name', 'email', 'mobile', 'password')    def create(self, validated_data):        user = super(UserSerializer, self).create(validated_data)        user.set_password(validated_data['password'])        user.save()        return user

views.py

from rest_framework import genericsfrom rest_framework.permissions import AllowAnyfrom .models import Userfrom .serializers import UserSerializerclass UserCreateAPIView(generics.CreateAPIView):    queryset = User.objects.all()    serializer_class = UserSerializer    permission_classes = (AllowAny,)