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

2024-01-25

我正在与 Django 用户合作,当我使用以下命令创建用户时,我已经对密码进行了哈希处理Django REST Framework我重写了create and update我的序列化器上的方法来哈希我的密码用户

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 身份验证和 Django 管理登录或登录。

如何对我的密码进行哈希处理并通过 Django REST FRamework 登录?

此致


添加其余框架身份验证设置,还包含以下内容

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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Django REST Framework 创建用户 - 不进行身份验证 的相关文章

随机推荐