这是我的 URLS.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^CMS/', include('CMSApp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
这是 CMSApp/urls.py:
from django.conf.urls import url
from django.conf.urls import include
from CMSApp import views
urlpatterns = [
url(r'^$', views.HomePageView.as_view()),
url(r'^users$', views.user_list.as_view()),
url(r'^users/(?P<pk>[0-9]+)$', views.user_detail.as_view()),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
我的 HomePageView 服务于这个 home.html 页面:
<h3>Register</h3>
<form ng-submit="ctrl.add()" name="myForm">
<label>Username</label>
<input type="text" name="uname" ng-model="ctrl.user.username" required>
<label>Password</label>
<input type="password" name="pwd" ng-model="ctrl.user.password" required>
<label>Email</label>
<input type="email" name="mail" ng-model="ctrl.user.email" required>
<input type="submit" value="Register">
</form>
<h3>Login</h3>
<form ng-submit="ctrl.loginUser()" name="myLoginForm">
<label>Username</label>
<input type="text" name="uname" ng-model="ctrl.user.username" required>
<label>Password</label>
<input type="password" name="pwd" ng-model="ctrl.user.password" required>
<input type="submit" value="Login">
</form>
<script>
angular.module("notesApp", [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}])
.controller("MainCtrl", ["$http", function($http) {
var self = this;
self.users = {};
var fetchUsers = function() {
return $http.get("/CMS/users").then(function(response) { // get list of existing users
self.users = response.data;
}, function(errResponse) {
console.error("Error while fetching users.");
});
};
self.loginUser = function() {
$http.post("/CMS/api-auth/login/", self.user)
.error(function(data, status, headers, config) {
console.log(data);
})
.then(fetchUsers);
console.log("Success Login with ", self.user);
};
}]);
</script>
当我注册一个已经存在的用户时,Django 返回一个 400 Bad Request 错误,这很好,因为我在前端使用 AngularJS 来处理 400 状态代码。
问题是,当我尝试使用不正确的用户名和密码(用户名不存在或用户名和密码不匹配)登录时,Django 返回 200 OK 状态码,因此我无法使用前端的 AngularJS。知道为什么当我尝试使用不正确的用户名和密码登录时 Django 返回 200 OK 吗?提交错误的用户名/密码时,如何让 Django 返回 400?
编辑:这是我原来的帖子:Django Rest Framework + AngularJS not logging user in or throwing errors and charlietfl 评论说“至于 ajax 错误处理。如果登录失败......使用真正的 REST 方法会发回 401 status 然后会触发您的 ajax 错误处理程序”,这就是为什么我在登录失败时不想要 200 OK 的原因。