如何使用 django rest 框架和自定义用户模型创建新用户
How to create a new user with django rest framework and custom user model
我有一个自定义用户模型,我正在使用 django-rest-framework 创建 API
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:
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)
但是,当我尝试创建新用户时出现此错误:
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 字段。但是,我如何创建一个 API 来使用 django-rest-framework 创建一个新用户?
我认为一个密码字段就足够了。如果要检查用户两次输入的密码是否相同,请在前端进行。您可以从序列化器中覆盖 create
方法,如下所示。
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,)
我有一个自定义用户模型,我正在使用 django-rest-framework 创建 API
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:
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)
但是,当我尝试创建新用户时出现此错误:
Got a
TypeError
when callingUser.objects.create()
. This may be because you have a writable field on the serializer class that is not a valid argument toUser.objects.create()
. You may need to make the field read-only, or override the UserSerializer.create() method to handle this correctly.
这可能是因为用户模型中没有 password1 或 password2 字段。但是,我如何创建一个 API 来使用 django-rest-framework 创建一个新用户?
我认为一个密码字段就足够了。如果要检查用户两次输入的密码是否相同,请在前端进行。您可以从序列化器中覆盖 create
方法,如下所示。
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,)