在django中使用自定义身份验证的用户名错误

在django中使用自定义身份验证的用户名错误

问题描述:

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

I'm trying to create custom authentication in Django where the identifier is an email, there is a required field called name and a password field. The login view works fine, but I get an error username from the forms.

这是我的views.py

Here is my 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

Here is my 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 。这里有什么问题?

This prints the error username. What's wrong here?

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

You'll need to create your own form instead of using django's own UserCreationForm. Django's form requires you to have a username.

您没有用户名,因此Django的表单将不适合您。所以...创造自己的。另请参阅 Django 1.5:UserCreationForm&自定义认证模型,特别是 https://*.com/a/16570743/27401 的答案。

You don't have a username, so Django's form will not work for you. So... create your own. See also Django 1.5: UserCreationForm & Custom Auth Model, and especially the answer https://*.com/a/16570743/27401 .