1

我按照这个来创建我的 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>
4

1 回答 1

0

I'm trying to build out a front end in Backbone for a Django 1.5 app.

I understand the Tastypie stuff and have been able to get that working, but I'm not sure how the page knows if the user is logged in or not when the page is first visited. I am using Session storage - is this incompatible with a JavaScript front end? Do I need to manually store the CSRF token and delete it after the user logs in, am I forced to use Django's (non-Ajax) for login/logout and then redirect to a protected, django served page with the JavaScript app code?

I am serving the JavaScript from django now, to get the CSRF token.. So I think I'm on the right path.

于 2013-09-06T04:44:17.423 回答