我有一个自定义用户模型,我使用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)
但是,当我尝试创建新用户时,我收到此错误:
在致电
TypeError
时获得User.objects.create()
。这可能是因为序列化程序类上的可写字段不是User.objects.create()
的有效参数。您可能需要将该字段设置为只读,或覆盖UserSerializer.create()方法以正确处理此字段。
这可能是因为User模型中没有password1或password2字段。但是,如何创建API以使用django-rest-framework创建新用户?
答案 0 :(得分:21)
我认为一个密码字段就足够了。如果要检查用户的两次密码输入是否相同,请在前端进行。您可以从序列化程序覆盖create
方法,如下所示。
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
@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
serialized = UserSerializer(data=request.data)
if serialized.is_valid():
serialized.save()
return Response(serialized.data, status=status.HTTP_201_CREATED)
else:
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
答案 1 :(得分:1)
在model.py中:
from django.contrib.auth.models import User
from django.db import models
STATUS_CHOICES = (
('inprogress', 'In Progress'),
('close', 'Close'),
('cancelled', 'Cancelled'),
)
class Task(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='inprogress')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
在views.py中 从rest_framework导入泛型
from tasks.models import Task
from tasks.serializers import TaskSerializer
class TaskList(generics.ListCreateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer
def create(self, request, *args, **kwargs):
# your custom implementation goes here
return Response(response)
class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer