2014-03-28 31 views
1

我想在Django中创建自定义身份验证,其中标识符是一个电子邮件,有一个称为名称和密码字段的必填字段。登录视图工作正常,但注册视图重定向回到同一页面。使用自定义身份验证的注册视图重定向回注册页面

这里是我的views.py

def auth_login(request): 
    if request.method == 'POST': 
     email = request.POST['email'] 
     password = request.POST['password'] 
     user = authenticate(email=email, password=password) 
     if user is not None: 
      login(request, user) 
      return HttpResponseRedirect("/tasks/") 
     else:   
      return HttpResponse('Invalid login.') 
    else: 
     form = UserCreationForm() 
    return render(request, "registration/login.html", { 
     'form': form, 
    }) 

def register(request): 
    if request.method == 'POST': 
     form = UserCreationForm(request.POST) 
     if form.is_valid(): 
      new_user = form.save() 
      new_user = authenticate(email=request.POST['email'], password=request.POST['password1']) 
      login(request, new_user) 
      return HttpResponseRedirect("/tasks/") 
    else: 
     form = UserCreationForm() 
    return render(request, "registration/register.html", { 
     'form': form, 
    }) 

这里是我的register.html

<form class="form-signin" role="form" method="post" action=""> 
    {% csrf_token %} 
    <h2 class="form-signin-heading">Create an account</h2> 
    <input type="text" name="name" maxlength="30" class="form-control" placeholder="Username" required autofocus> 
    <br> 
    <input type="email" name="email" class="form-control" placeholder="Email" required> 
    <br> 
    <input type="password" name="password1" maxlength="4096" class="form-control" placeholder="Password" required> 
    <br> 
    <input type="password" name="password2" maxlength="4096" class="form-control" placeholder="Password confirmation" required> 
    <input type="hidden" name="next" value="/tasks/" /> 
    <br> 
    <button class="btn btn-lg btn-primary btn-block" type="submit">Create the account</button> 
</form> 

有什么不对吗?

回答

0

Reinout van Rees's答案here工作完全正常。

您需要创建自己的表单而不是使用django自己的表格 UserCreationForm。 Django的表单要求你有一个用户名。

您没有用户名,因此Django的表单不适合您。 所以...创建你自己的。另请参阅Django 1.5:UserCreationForm & Custom Auth Model,尤其是答案 https://stackoverflow.com/a/16570743/27401

0

而不是

new_user = authenticate(email=request.POST['email'], password=request.POST['password1']) 

尝试

new_user = authenticate(email=form.cleaned_data['email'], password=form.cleaned_data['password1']) 
+0

这没有什么区别。它仍然重定向到注册页面。 –

+0

在注册方法中放置了一个用于表单验证的else语句。这真的有效吗? –

+0

你说得对,表格无效。任何线索为什么? –

相关问题