user3016988 user3016988 - 19 days ago 4x
Ajax Question

Django doesn't keep User logged in between views

I am quite new to web programming and django especially. I am trying to implement symple login service using Ajax. The user seems to be logged in succesfully however when the view is changed he uppears ulogged again.

Appreciate any help.

Login template:

<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>

Login Ajax:

function login(e) {
var username = $("#usernamelog").val();
var pwd = $("#pwdlogin").val();
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'));
url : "/loginscript/",
type : "post",
data : {
username: username,
password : pwd,
}).done(function(data) {
if (data == "good") {
document.getElementById('usernamelog').value ="good";
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));
return cookieValue;

Loginscript view:

def loginscript(request):
#c = {}
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:
if User.is_authenticated:
print >> sys.stderr,"should be good actually"
print >> sys.stderr, "Still not"
return HttpResponse("good")

print >> sys.stderr,"Should be bad"
return HttpResponse("bad")

Ehealth view:

def index(request):
if check!=True:
return redirect('')

return render (request=request, template_name=template)

The log I get:

Hey we are in login
[04/Oct/2016 14:02:42] "GET /login/ HTTP/1.1" 200 6881
script entered
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

So the user is logged in and then redirected back to login page as unlogged


User.is_authenticated is always true by definition, because you're calling it on the class. You need to check the method on the actual user instance: in your login view that is user, but in the index view that will be request.user.

However an even easier way to check the authentication in the index view is to use the login_required decorator.