【问题标题】:username error using custom authentication in django在 django 中使用自定义身份验证的用户名错误
【发布时间】:2014-05-07 15:16:55
【问题描述】:

我正在尝试在 Django 中创建自定义身份验证,其中标识符是电子邮件,有一个名为 name 的必填字段和一个密码字段。登录视图工作正常,但我从表单中收到错误username

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

{% if form.errors %}
    {% for error in form.errors %}
            {{ error }}                     
        {% endfor %}
{% endif %}

这将打印错误username。这里有什么问题?

【问题讨论】:

  • html 表单中没有username 字段,UserCreationForm 中可能需要。
  • 在自定义身份验证系统的情况下,注册视图如何工作?

标签: python html django


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 2016-07-05
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 2016-07-30
    相关资源
    最近更新 更多