我对网络编程和django尤其陌生。我正在尝试使用Ajax实现symple登录服务。用户似乎已成功登录,但是当视图发生变化时,他又重新开始篡改。Django不保留用户在视图之间登录
感谢任何帮助。 谢谢。
登录模板:
<form class="login-form" action="">
{% csrf_token %}
<input type="text" id="usernamelog" />
<input type="password" id="pwdlogin" />
<button onclick="login(event)">login</button>
<p class="message">Not registered? <a href="#">Create an account</a></p>
</form>
登录阿贾克斯:
function login(e) {
e.preventDefault();
var username = $("#usernamelog").val();
var pwd = $("#pwdlogin").val();
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
url : "/loginscript/",
type : "post",
data : {
username: username,
password : pwd,
}
}).done(function(data) {
if (data == "good") {
document.getElementById('usernamelog').value ="good";
window.location='../ehealth'
}else{
document.getElementById('usernamelog').value ="bad";
}
});
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
Loginscript观点:
def loginscript(request):
#c = {}
#c.update(csrf(request))
print >> sys.stderr,"script entered"
username = request.POST['username']
password = request.POST['password']
print >> sys.stderr, username
user = authenticate(username=username, password=password)
if user is not None:
login(request=request,user=user)
if User.is_authenticated:
print >> sys.stderr,"should be good actually"
else:
print >> sys.stderr, "Still not"
return HttpResponse("good")
else:
print >> sys.stderr,"Should be bad"
return HttpResponse("bad")
EHEALTH观点:
def index(request):
check=User.is_authenticated
if check!=True:
return redirect('http://127.0.0.1:8000/login/')
template="index.html"
return render (request=request, template_name=template)
日志我得到:
Hey we are in login
[04/Oct/2016 14:02:42] "GET /login/ HTTP/1.1" 200 6881
script entered
Andrey
should be good actually
[04/Oct/2016 14:02:46] "POST /loginscript/ HTTP/1.1" 200 4
[04/Oct/2016 14:02:46] "GET /ehealth/ HTTP/1.1" 302 0
Hey we are in login
因此,用户登录,然后重定向回到登录页面,未登录
哦,非常感谢! – asakryukin