【问题标题】:Django class based views, POST method not allowed基于 Django 类的视图,不允许使用 POST 方法
【发布时间】:2016-05-20 07:30:19
【问题描述】:

我正在学习django。

我收到方法帖子不允许的 405 错误。我在视图类中定义了 POST,如下所示。

class LoginView(views.APIView):

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = HUserAuthSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

用户应用中的 urls.py 有以下内容:

url(r'^login/$', LoginView.as_view(), name='login'),

项目级别的 urls.py 有以下内容:

url(r'^users/', include(users_urls)),

这就是我的网址

http://localhost:8000/users/login/

我可以从上面的日志中看到 URL。

前端angularJS代码如下:

appData.service("signInService", function($http, $q) { 

this.signIn = function (signin) {

    var url = "http://localhost:8000/users/login/";
    console.log(url);

    var defer = $q.defer();

    $http.post(url, { 
          email: signin.email,
          password: signin.password}, 
               {callback:"JSON_CALLBACK", _dont_enforce_csrf_checks:"True"}, {post:{method: "JSONP"}})
        .success(function(response){
            defer.resolve(response);
        })
        .error(function(response){
            defer.reject(response);    
        })

      return defer.promise;
    };  

});

【问题讨论】:

  • 跑题了,django 有 djoser 身份验证系统
  • 能不能加个前端post request的sn-p代码?
  • 检查你的 urls.py 中你的 URL 的顺序......你可能在那里做错了什么......
  • @Naresh,我认为你是对的。如果我注释掉项目中的其他 URL,我就能走得更远。

标签: django django-rest-framework


【解决方案1】:

您是否可能发帖到http://localhost:8000/api/v1/users/login 而不是http://localhost:8000/api/v1/users/login/(注意尾部斜杠)

尝试修改

url(r'^login/$', LoginView.as_view(), name='login'),

到

url(r'^login/?$', LoginView.as_view(), name='login'),

【讨论】:

  • 谢谢 Zack,我确实在末尾有斜线。也试过了?$,没有变化,同样的错误
猜你喜欢
  • 2012-01-23
  • 1970-01-01
  • 2021-07-25
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 2019-02-12
  • 1970-01-01
相关资源
最近更新 更多