【问题标题】:DRF password not being set by set_password()set_password() 未设置 DRF 密码
【发布时间】:2019-05-14 07:22:14
【问题描述】:

我有以下问题:

为什么密码没有被散列?

为什么 save_password 没有设置密码?

platforms = Platform.objects.all()
platforms[2].is_active
>> True
platforms[2].password
>> 'efgh'
platforms[2].check_password("efgh")
>> False
platforms[2].set_password("abcd")
platforms[2].save()
platforms[2].check_password("abcd")
>> False
platforms[2].password
>> 'efgh'

models.py

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)
class Platform(AbstractUser):
    pass

serializers.py

class PlatformSerializer(serializers.ModelSerializer):
    class Meta:
        model  = Platform
        fields = ("username", "password")

        def create(self, validated_data):
            password = validated_data.pop('password')
            platform = Platform(**validated_data)
            platform.set_password(password)
            platform.save()
            return platform

views.py

class CreatePlatform(viewsets.ModelViewSet):
    queryset           = Platform.objects.all()
    serializer_class   = PlatformSerializer
    pagination_class   = None
    permission_classes = (AllowAny, )

在我的 settings.py 我有 AUTH_USER_MODEL = 'users.Platform'

PS:创建的Token就好了

【问题讨论】:

    标签: python django authentication django-rest-framework


    【解决方案1】:
    p = platforms[2]  
    p.set_password("abcd")
    p.save()
    p.check_password("abcd")
    >> True
    

    【讨论】:

    • 但这到底是什么,这是?为什么它没有像我一样被保存?
    • 这是因为每个切片操作都会对数据库进行一次新查询并返回一个新对象。所以平台[2] 没有连接到后续平台。
    • 哇!!从来不知道这一点,你能指点我一些文档吗?非常感谢您对我的启发
    • docs.djangoproject.com/en/2.2/topics/db/queries/… 如您所见,每个切片都命中数据库
    猜你喜欢
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多