Django: request.user not installed after redirect

In particular, after authentication and redirection, request.user is an anonymous user.

login (viewing function)

def login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): #django.contrib.auth.login Login(request, form.get_user()) str = reverse('cm_base.views.index') return HttpResponseRedirect(str) else: # Their password / email combination must have been incorrect pass else: form = LoginForm() return render_to_response('cm_base/login.html', {"DEBUG": True, 'form' : form }, context_instance=RequestContext(request)) 

in the index view, I removed the login_required decorator and tested the request.user object

 def index(request): test = request.user.is_authenticated() return render_to_response('cm_base/index.html', {"DEBUG": True, "user": request.user,}, context_instance=RequestContext(request)) 

The test returns false.

Fix

I just called directly to the index. I was still confused as to why the user object was lost when I called HttpResponseRedirect.

 def login(request): if request.method == 'POST': form = LoginForm(request.POST) # Not shown in this example if form.is_valid(): Login(request, form.get_user()) str = reverse('cm_base.views.index') return index(request) else: # Their password / email combination must have been incorrect pass else: form = LoginForm() 
+7
source share
3 answers

A lot is happening here, which should not be. First, you do not need to pass request.user , which is available by default, if you use the RequestContext that you are.

Login() this method, what exactly does it do? Django provides a built-in login method that you should use if using the default authentication server.

You also do not check if the user is on or off.

Here is another version of your code, adapted from an example in the documentation :

 from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login def login_view(request): form = LoginForm(request.POST or {}) ctx = {'form': form} if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username, password) if not user: ctx['errors'] = 'Invalid Login' return render(request, 'login.html', ctx) if not user.is_active: ctx['errors'] = 'User is locked' return render(request, 'login.html', ctx) login(request, user) return redirect('home') else: return render(request, 'login.html', ctx) 
+3
source

What database are you using? If this is something other than ModelBackend, make sure your get_user method is correct. It seems that the auth middleware sends a different identifier (like pk instead of username) than the one you are looking for in the get_user method.

0
source

It was a fix.

 <link rel="icon" href="{{ STATIC_URL }}img/favicon.ico" /> 

This file was not in the static directory. As a result, 404 user session was broken.

-one
source

All Articles