我正在学习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。
frontend 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;
};
});
答案 0 :(得分: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'),