Brandon Taylor
unread,Jan 13, 2009, 12:43:58 PM1/13/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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