如何使用Django Rest框架和自定义用户模型创建新用户

问题描述:

我有一个自定义用户模型,我正在使用django-rest-framework创建API

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

models.py:

models.py:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        unique=True,
        max_length=254,
    )
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=15)
    mobile = models.IntegerField(unique=True)
    date_joined = models.DateTimeField(default=timezone.now)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

serializers.py:

serializers.py:

class UserSerializer(serializers.ModelSerializer):
    password1 = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'mobile', 'password1', 'password2')

views.py:

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        User.objects.create_user(
            serialized.save()
        )
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

但是,当我尝试创建新用户时,出现此错误:

However, when I try to create a new user I am getting this error:


调用 User.objects.create()时出现 TypeError 。这可能是因为序列化程序类上有一个可写字段,该字段不是 User.objects.create()的有效参数。您可能需要将该字段设置为只读,或重写UserSerializer.create()方法才能正确处理此问题。

Got a TypeError when calling User.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to User.objects.create(). You may need to make the field read-only, or override the UserSerializer.create() method to handle this correctly.

因为用户模型中没有password1或password2字段。但是,如何使用django-rest-framework创建API来创建新用户呢?

This maybe because there's no password1 or password2 fields in the User model. But so, how can I create an API to create a new user using django-rest-framework?

我认为一个密码领域就足够了。如果要检查用户两次输入的密码是否相同,请在前端进行。您可以像下面这样从序列化程序中覆盖 create 方法。

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,)