如何使用django内置表单?

时间:2012-11-03 06:33:17

标签: django django-forms

我正在尝试使用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')   

但这不是如何使用身份验证表单,至少不是正确的方式。

1 个答案:

答案 0 :(得分: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')
相关问题