Login form on every page and session weirdness

5 views
Skip to first unread message

Brandon Taylor

unread,
Jan 13, 2009, 12:43:58 PM1/13/09
to Django users
Hi everyone,

I have a login form on every page and want to leverage the
AuthenticationForm from contrib.auth. So, I thought I would have a
middleware tier to process the request and check for a GET or POST and
create the appropriate form, either bound or un-bound. Here is my
middleware:

from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import logout, authenticate, login

class LoginMiddleware(object):
def process_request (self, request):
if request.method == 'POST':
if request.POST.get('login', False):
authentication_form = AuthenticationForm
(data=request.POST)

if authentication_form.is_valid():
login(request, authentication_form.get_user())
else:
request.session['authentication_form'] =
authentication_form

if request.POST.get('logout', False):
logout(request)

return HttpResponseRedirect(request.path)

else:
try:
authentication_form = request.session
['authentication_form']
except KeyError:
request.session['authentication_form'] =
AuthenticationForm(request)


This part works as expected. However, the really challenging part has
been displaying the errors for the form. I added a Context Processor:

def get_login_messages(request):

new_dict = {
'authentication_form' : request.session
['authentication_form'],
}

return new_dict

To return the form instance that was set in session and pass it to the
template. If I print the session 'authentication_form' from the
console in my middleware if the form is invalid, the session is
correct. It contains an instance of the form with all of the error
messages.

But, when I print the session from the Context Processor, I get the un-
bound instance of the form, *without* error messages.

Can anyone see what I'm doing wrong here? I have no idea what's
happening to the "authenticated_form" session from the time it is set
by the middleware and reaches the context processor.

Help GREATLY appreciated,
Brandon

Brandon Taylor

unread,
Jan 13, 2009, 3:30:06 PM1/13/09
to Django users
Turns out I had my session backend specified wrong, so my sessions
were never being saved. However, I did run into a new problem - it
doesn't seem that a form object can be put into session?

Can anyone verify that this is true? When trying to stuff the form
object into session, I ran into pickling errors.
Reply all
Reply to author
Forward
0 new messages