【问题标题】:The `request` argument must be an instance of `django.http.HttpRequest`, not `builtins.str``request` 参数必须是 `django.http.HttpRequest` 的实例,而不是 `builtins.str`
【发布时间】:2022-06-26 16:05:23
【问题描述】:

请帮我解决这个问题。提前致谢。

在这里,如果电话号码存在,则表明它存在,否则会向我抛出错误,例如:
`/validate_phone/ 处的断言错误

请求参数必须是 django.http.HttpRequest 的实例,而不是 builtins.str。 `

@permission_classes((permissions.AllowAny,))
class ValidatePhoneSendOTP(APIView):

    def post(self, request, *args, **kwargs):
        phone_number = request.data.get('phone')  

        if phone_number:
            phone = str(phone_number)
            user = UserModel.objects.filter(phone__iexact=phone)
            if user.exists():
                return Response({
                    'status': False,
                    'detail': 'Phone number already exists'
                })
            else:
                key = send_otp(phone)
                if key:
                    old = PhoneOTP.objects.filter(phone__iexact=phone)
                    if old.exists():
                        old = old.first()
                        count = old.count()
                        if count > 10:
                            return Response({
                                'status': False,
                                'detail': "Sending otp error. Limit exceeded. Please contact customer support."
                            })
                        old.count = count + 1
                        old.save()
                        print("count increase", count)
                        return Response({
                            'status': True,
                            'detail': "OTP sent successfully."
                        })
                    else:
                        PhoneOTP.objects.create(
                            phone=phone,
                            otp=key,
                        )
                        return Response({
                            'status': True,
                            'detail': 'OTP sent successfully'
                        })

【问题讨论】:

标签: python django django-rest-framework django-views


【解决方案1】:

问题是你用 @permission_classes((permissions.AllowAny,)) 装饰类,这会生成一些 str 并且它通过你的 api 类,期望 django.http.HttpRequest

apiview上权限的使用是

from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

from [drf documentation][1]


  [1]: https://www.django-rest-framework.org/api-guide/permissions/

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2020-10-10
    • 2015-10-16
    • 2021-04-08
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多