使用自定义身份验证注册视图重定向回注册页面

时间:2014-03-28 07:44:48

标签: python html django

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

这是我的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>

这里有什么问题?

2 个答案:

答案 0 :(得分: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'])

答案 1 :(得分:0)

Reinout van Rees's回答here完全正常。

  

您需要创建自己的表单,而不是使用django自己的表单   UserCreationForm。 Django的表单要求您拥有用户名。

     

您没有用户名,因此Django的表单不适合您。   所以......创造你自己的。另见Django 1.5:UserCreationForm&amp;习惯   Auth Model,尤其是答案   https://stackoverflow.com/a/16570743/27401