1

django 組み込みの AuthenticationForm を使用して、ユーザーがメール アドレスとパスワードを使用してログインできるようにしようとしています。ユーザーを認証するためにユーザー名と電子メールの両方を受け入れるように認証機能を変更しました。

これまでの私のコードは次のとおりです。

     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')   

しかし、これは認証フォームの使用方法ではなく、少なくとも正しい方法ではありません。

4

1 に答える 1

0

例。脱線の django.contrib.auth.forms を確認できます (forms.py ファイルで AuthenticationForm を検索してください)。

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.

したがって、コードを次のように変更します。

 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 に答える