如何从数据库中查询当前用户-Django

问题描述 投票:0回答:2

我目前处于修复状态,需要您的帮助。我正在使用 Django_rest_framework 开发 API,目前在注册模块上。下面的代码是重新生成 OTP 并发送给当前用户的功能。但是,我无法访问当前用户,但我在数据库中有他的详细信息……例如:phone_number、is_active=False、is_verified=False。我希望能够使用他的电话号码访问用户,然后重新生成 OTP 并在 OTP 过期后发送到他的电话号码。

# regenerate OTP
class RegenerateOTP(APIView):
    @swagger_auto_schema(
        operation_summary="This endpoint is responsible for regenerating OTP if expired",
        operation_description="This endpoint regenerate OTP after expiration period",
    )
    def post(self, request):
        instance = CustomUser.objects.filter(is_active=False).first()
        if int(instance.max_otp_try) == 0 and timezone.now() < instance.otp_max_out:
            return Response(
                "Max OTP try reached, try after an hour.",
                status=status.HTTP_400_BAD_REQUEST,
            )
        otp = generateRandomOTP(100000, 999999)
        otp_expire = timezone.now() + timedelta(minutes=10)
        max_otp_try = int(instance.max_otp_try) - 1

        instance.otp = otp
        instance.otp_expire = otp_expire
        instance.max_otp_try = max_otp_try

        if max_otp_try == 0:
            instance.otp_max_out = timezone.now() + datetime.timedelta(hours=1)
        elif max_otp_try == -1:
            instance.max_otp_try = settings.MAX_OTP_TRY
        else:
            instance.otp_max_out = None
            instance.max_otp_try = max_otp_try
        instance.save()
        send_otp(instance.phone_number, otp)
        return Response(
            "successfully re-generated the new otp", status=status.HTTP_200_OK
        )

我已经尝试在会话或缓存中注册时保存用户的电话号码,因此我总是可以通过以下方式在该视图中取回它:

phone_number = request.session.get('phone_number) and then pass it on to,
instance = CustomUser.objects.filter(phone_number=phone_number).first()

我现在的问题是,我明白这不是在我脑海中实现规模化的更好方法。我需要一个更好的方法来解决这个挑战。非常感谢您的帮助。

javascript python django django-rest-framework django-templates
2个回答
0
投票

您可以将

phone_number
中的
CustomUser
字段设置为唯一,并使用
CustomUser.objects.get(phone_number=phone_number)
。您应该将其设置为唯一,因为您希望通过电话号码访问特定用户。无论如何,电话号码不应该重复。

那会比你现在拥有的更好。


0
投票

为什么需要当前用户发送一次性密码?注册需要opt吗?如果注册需要 OTP,请不要从数据库中获取用户。只需获取电话号码并将 OTP 发送到该电话号码即可。如果您需要当前用户发送 OTP,则使 phone_number 字段在表中唯一并使 db_index=True 并使用

CustomUser.objects.get(phone_number=phone_number)
, 不要在这上面使用 filter 因为 filterget 贵得多并且还使用 try catch 块来获取当前用户。

© www.soinside.com 2019 - 2024. All rights reserved.