authentication - Django : request.user not set after redirect -
specifically, after authentication , redirect, request.user anonymous user.
login (view 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: # 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 index view, removed login_required decorator , tested 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))
test returns false.
fix
i ended calling index view directly. still confused why user object lost when called httpresponseredirect.
def login(request): if request.method == 'post': form = loginform(request.post) # not shown in example if form.is_valid(): login(request, form.get_user()) str = reverse('cm_base.views.index') return index(request) else: # password / email combination must have been incorrect pass else: form = loginform()
a lot of things going on here shouldn't be. first, don't need pass request.user
, available default long using requestcontext
, are.
login()
method, doing? django provides built-in login
method should using if using default authentication backend.
you not checking if user enabled or disabled.
here different version of code, adapted example in documentation:
from django.shortcuts import render, redirect 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 locked' return render(request, 'login.html', ctx) login(request, user) return redirect('home') else: return render(request, 'login.html', ctx)
Comments
Post a Comment