2012-11-03 2 views
1

django inbuilt AuthenticationForm을 사용하여 사용자가 전자 메일 주소와 암호를 사용하여 로그인 할 수있게하려고합니다. 사용자 인증을 위해 사용자 이름과 전자 메일을 모두 받아들이도록 authenticate 함수를 변경했습니다.django inbuilt forms를 사용하는 방법?

이 지금까지 내 코드입니다 :

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

는하지만이 인증 양식, 적어도 올바른 방법을 사용하지 방법이다.

답변

0

예. derails에 대한 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. 

그래서, 당신의 코드를 수정 : 호출되는 어떠한 POST 방법이없는 경우

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

이 마지막 줄이 실행되지 않습니다? – heaven00

+0

@ user1702796 네, 맞습니다. 실행될 수 있습니다. – sergzach

관련 문제