我有一個自定義的用戶模型,我使用Django的REST的框架來創建API如何創建Django的REST框架和自定義用戶模型的新用戶
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.
這也許是因爲有在用戶模型中沒有密碼1或密碼2場。但是,如何創建一個API來使用django-rest-framework創建一個新用戶?
那麼,如何使用它的看法? – Aamu
我編輯我的答案,請嘗試。 – Guinner