Django Rest Framework注册

时间:2018-04-24 09:24:28

标签: django django-rest-framework django-rest-auth

我有自定义用户模型

class User(AbstractUser):

    username = None    
    email = models.EmailField( unique=True)    
    phone = models.CharField( max_length=15) 
    is_pro = models.BooleanField(default=False)    

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['phone']

    objects = UserManager()

    @property
    def token(self):
    """
    Allows us to get a user's token by calling `user.token` instead of
        `user.generate_jwt_token().

    The `@property` decorator above makes this possible. `token` is called
    a "dynamic property".
    """
        return self._generate_jwt_token()

    def _generate_jwt_token(self):
        """
        Generates a JSON Web Token that stores this user's ID and has an expiry
        date set to 60 days into the future.
        """
        import jwt
        from datetime import datetime, timedelta
        from django.conf import settings
        dt = datetime.now() + timedelta(days=60)

        token = jwt.encode({
            'id': self.pk,
            'exp': int(dt.strftime('%s'))
        }, settings.SECRET_KEY, algorithm='HS256')

        return token.decode('utf-8')

现在我尝试使用本教程https://thinkster.io/tutorials/django-json-api/authentication

使用Django Rest Framework制作SignIn API

serializer.py

class RegistrationSerializer(serializers.ModelSerializer):

    password = serializers.CharField(
        max_length=128,
        min_length=8,
        write_only=True
    )


    token = serializers.CharField(max_length=255, read_only=True)

    class Meta:
        model = User

        fields = ['email', 'phone', 'password', 'token']

    def create(self, validated_data):
        # Use the `create_user` method we wrote earlier to create a new user.
        return User.objects.create_user(**validated_data)

views.py

class RegistrationAPIView(APIView):
    # Allow any user (authenticated or not) to hit this endpoint.
    permission_classes = (AllowAny,)    
    serializer_class = RegistrationSerializer

    def post(self, request):
        user = request.data.get('user', {})

        serializer = self.serializer_class(data=user)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)

然后我创建了一个新用户,发生错误“此字段是必需的。”对于我的所有用户字段,如电子邮件,电话,密码。 截图图片http://joxi.ru/12MOMkZt4eeBEr

1 个答案:

答案 0 :(得分:1)

这是因为您在User模型中设置此字段不可为空且必需。要修复此问题,您可以将blank=True个参数添加到可能为空的字段中,例如phone

class User(AbstractUser):

    username = None    
    email = models.EmailField(unique=True)    
    phone = models.CharField(max_length=15, blank=True) 
    is_pro = models.BooleanField(default=False)    

在此次运行makemigrationsmigrate之后,在数据库级别应用更改。

<强> UPD

在视图中,您需要直接从request.data获取数据:

def post(self, request):
    serializer = self.serializer_class(data=request.data)
    serializer.is_valid(raise_exception=True)
    serializer.save()

    return Response(serializer.data, status=status.HTTP_201_CREATED)

request.data不包含user密钥,因此request.data.get('user', {})会返回空字典。