jango默认的Authenticaiton表单显示用户名而不是

jango默认的Authenticaiton表单显示用户名而不是

本文介绍了django默认的Authenticaiton表单显示用户名而不是电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用django实施了自己的用户登录表单,如下所示

I implemented my own user login form with django like below

from django.contrib.auth.forms import AuthenticationForm

class CustomUserLoginForm(AuthenticationForm):
    class Meta:
        model = CustomUser
        fields = ('email', 'password')

然后,这就是我所拥有的:

then as a view this is what I have:

from rest_auth.views import LoginView
from users.forms import CustomUserLoginForm

class CustomLoginView(LoginView):
    def get(self, request):
        form = CustomUserLoginForm()
        return render(request, "api/test_template.html", context={"form": form})

然后在模板中

,我在<form>标记中调用{{form.as_p}}以显示表单输入详细信息.

in my template then, I am calling {{form.as_p}} in <form> tag to show the form input details.

但是,默认情况下,它显示用户名和密码形式.如何用电子邮件替换用户名?

However, by default, this shows the username and password forms. How can I replace the username with the email?

在rest-auth,可浏览的api中,用户名和电子邮件都存在,所以我知道我可以这样做,因为我将rest-auth LoginView用作后端.

in the rest-auth, browserable api, both the username and the email are present so I know that I can do this since I am using the rest-auth LoginView as backend.

我可以手动打开{{form}}的包装,因为以后我仍然想样式化此表单.我该怎么办?

Can I manually unpack {{form}} since later I would still like to style this form. How can I do this?

我本人在`api/test_template.html中解压缩了表单,如下所示:

I unpacked the form in `api/test_template.html myself which now looks like the below:

{% block content %}

    <div class="container">
        <form method="POST">
        {% csrf_token %}
            <div>
                <label for="{{ form.email.id_for_label }}">Email: </label>
                <input{{ form.email }}>
            </div>

            <div>
                <label for="{{ form.password.id_for_label }}">password: </label>
                <input type="password" {{ form.password }}>
            </div>

            <button style="background-color:#F4EB16; color:blue" class="btn btn-outline-info" type="submit">Login</button>
        </form>
        Don't have an account? <a href="/register" target="blank"><strong>register here</strong></a>!
    </div>
{% endblock %}

这有效,但是,rest-auth框架仍然要求用户名不能为空.我该如何更改它以忽略用户名?

this works, however, rest-auth framework still require the username to not be empty. how can I change that, to ignore the username?

from django.contrib.auth.models import AbstractUser
from django.db import models


class CustomUser(AbstractUser):

    def __str__(self):
        return self.email

推荐答案

您应该在CustomUser模型上设置USERNAME_FIELD='email'.

You should set USERNAME_FIELD='email' on your CustomUser model.

如何使用电子邮件作为用户名.

这篇关于django默认的Authenticaiton表单显示用户名而不是电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 04:27