django default Authenticaiton form shows username rather than email

試著忘記壹切 提交于 2020-01-16 09:48:06

问题


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})

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?

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.

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

update

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 %}

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

my user model

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


class CustomUser(AbstractUser):

    def __str__(self):
        return self.email

回答1:


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

There is nice blogpost on How to use email as username.



来源:https://stackoverflow.com/questions/57942640/django-default-authenticaiton-form-shows-username-rather-than-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!