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

后端 未结 1 1947
野性不改
野性不改 2020-12-13 19:15

I have a custom user model and I am using django-rest-framework to create API

models.py:

class User(AbstractBaseUser, PermissionsMixin):
    email =          


        
相关标签:
1条回答
  • 2020-12-13 19:49

    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 serializers
    
    class 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 generics
    from rest_framework.permissions import AllowAny
    from .models import User
    from .serializers import UserSerializer
    
    class UserCreateAPIView(generics.CreateAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer
        permission_classes = (AllowAny,)
    
    0 讨论(0)
提交回复
热议问题