1

I am trying to use the django inbuilt AuthenticationForm to allow users to login using their email address and password. I have changed the authenticate function to accept both username and email to authenticate users.

This is my code so far:

     def loginuser(request):
          if request.POST:
            """trying to use AuthenticationForm to login and add validations"""
            form = AuthenticationForm(request.POST.get('email'),request.POST.get('password'))
            user = form.get_user()
            if user.is_active:
                login(request,user)
                render_to_response('main.html',{'user':user})
            else:
                HttpResponse('user not active') 
          render_to_response('login.html')   

But this is not how the authentication form is used, at least not the correct way.

4

1 回答 1

0

An example. You can see django.contrib.auth.forms for derails (search AuthenticationForm in the file forms.py).

f = AuthenticationForm( { 'username': request.POST.get( 'email' ), 'password': request.POST.get( 'password' ) } )
try:
    if f.is_valid():
        login( f.get_user() )
    else:
        # authentication failed
except ValidationError:
    # authentication failed - wrong password/login or user is not active or can't set cookies.

So, modify your code to:

 def loginuser(request):
      if request.POST:
        """trying to use AuthenticationForm to login and add validations"""
        form = AuthenticationForm(request.POST.get('email'),request.POST.get('password'))
        try:
            if form.is_valid():
                # authentication passed successfully, so, we could login a user
                login(request,form.get_user())
                render_to_response('main.html',{'user':user})
            else:
                HttpResponse('authentication failed') 
        except ValidationError:
             HttpResponse('Authentication failed - wrong password/login or user is not active or can't set cookies')

      render_to_response('login.html')
于 2012-11-03T07:32:15.617 回答