使用Django REST Framework创建用户 - 不进行身份验证

时间:2017-01-20 04:30:21

标签: django django-rest-framework restful-authentication password-encryption

我正在与Django用户合作,当我使用Django REST Framework创建用户时,我已经对密码进行了哈希处理,并且我覆盖了序列化程序上的createupdate方法来哈希我的密码用户

class UserSerializer(serializers.ModelSerializer):
    #username = models.CharField()

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance


    class Meta:
        model = User
        fields = ('url', 'username', 'password', 'first_name','last_name',
                  'age', 'sex', 'photo', 'email', 'is_player', 'team',
                  'position', 'is_staff', 'is_active', 'is_superuser',
                  'is_player', 'weight', 'height', 'nickname',
                  'number_matches', 'accomplished_matches',
                  'time_available', 'leg_profile', 'number_shirt_preferred',
                  'team_support', 'player_preferred', 'last_login',
        )

我的views.py是这样的:

class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    filter_fields = ('username', 'is_player', 'first_name', 'last_name', 'team' , 'email', )

我的REST_FRAMEWORK设置为:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),

    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny',
    ),

    'PAGE_SIZE': 10
}

我不方便的是,当我通过rest框架创建和用户时,密码被哈希,但是我无法登录或通过rest authentication和Django admin登录。

如何散列密码并通过Djago REST FRamework登录?

最好的问候

1 个答案:

答案 0 :(得分:1)

添加休息框架认证设置,以及

'DEFAULT_AUTHENTICATION_CLASSES': ( 
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.SessionAuthentication', 
)

参考http://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication

对于令牌身份验证,请查看文档http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication