"detail": "方法 \"POST\" 不允许。"

Posted

技术标签:

【中文标题】"detail": "方法 \\"POST\\" 不允许。"【英文标题】:"detail": "Method \"POST\" not allowed.""detail": "方法 \"POST\" 不允许。" 【发布时间】:2020-06-17 06:14:26 【问题描述】:

在这里,我尝试在 djangorestfulapi 中使用自定义用户登录,但出现“详细信息”错误:“不允许方法 \"POST\"。” .谁能解释一下我哪里出错了?

class LoginAPIView(APIView):
    def user_login(self,request,format=None):
        # context = RequestContext(request)
        if request.method == 'POST':
            user = ''' SELECT * FROM users '''
            # Gather the username and password provided by the user.

            username = request.POST['username']
            password = request.POST['password']
            user = authenticate(username=username, password=password)
            print("auth",str(authenticate(username=username, password=password)))

            if user:
                # Is the account active? It could have been disabled.
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect('/')
            else:
                return HttpResponse("xxx")
        else:
            # Bad login details were provided. So we can't log the user in.
            print ("Invalid login details: 0, 1".format(username, password))
            return HttpResponse("Invalid login details supplied.")

端点网址:

path('api/login/',LoginAPIView.as_view(), name='login'),

【问题讨论】:

这能回答你的问题吗? 405 POST method not allowed 不,不是。 @Hedgy 【参考方案1】:

在基于类的视图中,您应该像这样为单独的 http 方法定义单独的方法

class LoginAPIView(APIView):
    def post(self,request,format=None):
        user = ''' SELECT * FROM users '''
            # Gather the username and password provided by the user.

        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        print("auth",str(authenticate(username=username, password=password)))

        if user:
            # Is the account active? It could have been disabled.
            if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/')
        else:
            return HttpResponse("xxx")

【讨论】:

谢谢你。但现在我在 /api/login/'username' 处收到 MultiValueDictKeyError 错误 这是因为你没有在你的post请求中发送usernamepassword 我没听懂。 您在username = request.POST.get('username') password = request.POST.get('password') 部分代码处遇到错误,这清楚地表明request.POST 没有所需的数据。您应该将该数据发送到您的视图。 @Psynora 现在我在 /api/login/ 'username' 处收到 MultiValueDictKeyError 错误 这听起来完全是一个不同的问题。

以上是关于"detail": "方法 \"POST\" 不允许。"的主要内容,如果未能解决你的问题,请参考以下文章

"detail": "Method \"GET\" not allowed. 在 django 中调用端点

"errors":"errors":["detail":"您无权执行此操作。","code":&qu

"detail": "未提供身份验证凭据。"创建新用户时

模型 \"Trains\ 的路径 \"setno\" 处的值 \" details: '233' \" 转换为字符串失败

为啥响应总是 "detail":"Unsupported media type \"text/plain\" in request." 在

"detail": "未提供身份验证凭据。"设置 uid 和 token 时出现此错误