2017-03-26 43 views
3

我有一個自定義的用戶模型,我使用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 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.

這也許是因爲有在用戶模型中沒有密碼1或密碼2場。但是,如何創建一個API來使用django-rest-framework創建一個新用戶?

回答

8

我覺得一個密碼字段就夠了。如果要檢查用戶的兩次密碼輸入是否相同,請在前端執行。您可以像下面那樣覆蓋序列化程序的一個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) 
+0

那麼,如何使用它的看法? – Aamu

+0

我編輯我的答案,請嘗試。 – Guinner

相關問題