我按照这个来创建我的 ajax 身份验证。ajax 不发送POST
数据;它发送一个空的querydict
. 如果我在我的 ajax 视图中明确地写下我的用户名和密码,它会完美地登录和退出......但这没用。
我找到了答案。这已针对 Django 1.5.1 进行了更新。下面的代码有效。
#Ajax_Views.py
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import HttpRequest
from django.conf.urls import url
from django.utils import simplejson
from tastypie.http import HttpUnauthorized, HttpForbidden
from tastypie.utils import trailing_slash
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['first_name', 'last_name', 'email']
allowed_methods = ['get', 'post']
resource_name = 'user'
authorization = Authorization()
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/login%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('login'), name="api_login"),
url(r'^(?P<resource_name>%s)/logout%s$' %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('logout'), name='api_logout'),
]
def login(self, request, **kwargs):
self.method_check(request, allowed=['post', 'ajax'])
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )
def logout(self, request, **kwargs):
self.method_check(request, allowed=['get'])
if request.user and request.user.is_authenticated():
logout(request)
return self.create_response(request, { 'success': True })
else:
return self.create_response(request, { 'success': False }, HttpUnauthorized)
#Jquery/Ajax
$('#send').click(function(e){
e.preventDefault();
data = {
"username": $('#username').val(),
"password": $('#password').val()
};
$.ajax({
type: "POST",
url: "http://127.0.0.1:8000/api/user/login/",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function(data) {console.log(data)},
error: function (rs, e) {console.debug(rs)}
});
});
#The HTML
<input type='text' id='username' />
<input type='password' id='password'/>
<input type='submit' id='send' class='btn' href='#'>Send</a>