Ajax Django Login/Authentication without re-direct(无需重定向的 Ajax Django 登录/身份验证)
问题描述
我正在尝试设置类似于 StackOverflow 的身份验证设置,其中正常浏览不会受到影响,除非有一些需要身份验证的特权操作(在此之前不要打扰用户).
I am trying to have an authentication set-up similar to that of StackOverflow, where the normal browsing is never affected unless there are some privileged actions which requires authentication (Do not bother users until then).
如果未登录,则应为登录",如果已登录,则应为用户名".
It should be as "Log In" if not logged in or "UserName" if logged in.
base.html 的相关部分(来自 fallr.net)(由 index.html 扩展)看起来像:
The relevant part of base.html (from fallr.net) (extended by index.html) looks like :
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
var methods = {
forms : function(){
var login = function(){
var user = $(this).children('form').children('input[type="text"]').val();
var pass = $(this).children('form').children('input[type="password"]').val();
var dataString = '&username=' + $('input[name=username]').val() + '&password=' + $('input[name=password]').val();
if(user.length < 1 || pass.length < 1){
alert('Invalid!
Please fill all required forms');
} else {
alert('username: '+user+'
password: '+pass);
$.ajax({
type: "POST",
url: "/login",
dataType: "html",
data: {
username : user,
password : pass,
csrfmiddlewaretoken : '{{ csrf_token }}'
},
success: function(json){alert (json.server_response);},
error: function(xhr,errmsg,err) { alert(xhr.status + ": " + xhr.responseText); }
});
$.fallr('hide');
return false;
}
}
$.fallr('show', {
icon : 'secure',
width : '320px',
content : '<h4>Sign in</h4>'
+ '<form>'
+ '<input name="username" placeholder="username" type="text"/'+'>'
+ '<input name="password" placeholder="password" type="password"/'+'>'
+ '</form>',
buttons : {
button1 : {text: 'Submit', onclick: login},
button4 : {text: 'Cancel'}
}
});
}
};
//button trigger
$('a[href^="#fallr-"]').click(function(){
var id = $(this).attr('href').substring(7);
methods[id].apply(this,[this]);
return false;
});
// syntax highlighter
hljs.tabReplace = ' ';
hljs.initHighlightingOnLoad();
});
//]]>
</script>
urls.py 看起来像:
The urls.py looks like :
from django.conf.urls import patterns, include, url
#from triplanner.views import *
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', main_page),
url(r'^login$',ajax_login),
url(r'^login/$','django.contrib.auth.views.login'),
url(r'^logout/$', logout_page),
# our application page
url(r'^account/',include('tripapp.urls')),
)
另外,'^login/$' 是以前的学习实现,我想用 Ajax 登录代替.
Also, '^login/$' is the previous implementation for learning which I want to replace with Ajax login.
还有我的views.py:
And my views.py:
# -*- coding: utf-8 -*-
from django.contrib.auth import logout
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
#from django.http import HttpResponse
from django.template import RequestContext
#from django.utils import simplejson
def main_page(request):
return render_to_response('index.html', context_instance=RequestContext(request))
def logout_page(request):
"""
Log users out and redirect them to the main page
"""
logout(request)
return HttpResponseRedirect('/')
def ajax_login(request):
"""
This view logs a user in using the POST data.
"""
if request.method == 'POST':
print request.POST['username']
username = request.POST['username']
password = request.POST['password']
print username
print password
user = authenticate(username=username, password=password)
if (not user is None) and (user.is_active):
login(request, user)
response_dict = {}
response_dict.update({'server_response': username})
#return HttpResponse(simplejson.dumps(response_dict),mimetype='applicaion/javascript')
return render_to_response('index.html',{'username' : user}, context_instance=RequestContext(request))
# Set Session Expiry to 0 if user clicks "Remember Me"
#if not request.POST.get('rem', None):
# request.session.set_expiry(0)
#data = username
else:
return render_to_response('index.html', context_instance=RequestContext(request))
我收到一个 403 错误,例如[20/Aug/2013 00:29:20] POST/HTTP/1.1"403 2294"
I am getting a 403 Error like "[20/Aug/2013 00:29:20] "POST / HTTP/1.1" 403 2294"
更新编号 1:
使用更改后的 urls.py、views.py 和 javascript,我能够得到 200 响应,但它给出的警告窗口显示未定义并提醒我阻止此页面创建对话框"
With the changed urls.py, views.py and javascript I am able to get a 200 response, but it gives alert window saying undefined and alerting me "Prevent this page from creatng dialog boxes"
推荐答案
我使用的方法是有一个 Tastypie api 层,需要对 API 进行身份验证.如果API调用因为认证失败,客户端可以通过ajax登录方式请求用户登录.
The approach I use is to have a Tastypie api layer and require authentication for the APIs. If the API call fails because of authentication, the client can request the user to log-in via the ajax login method.
您可以使用此 gist
这篇关于无需重定向的 Ajax Django 登录/身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无需重定向的 Ajax Django 登录/身份验证
基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01