如何更改LoginView中调用的AuthenticationForm标签,以及如何在LoginView中使用其他表单?(Django 3.0)

2024-04-18 21:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Django3.0,实际上我正在使用django.contrib.auth.views.LoginView

这是我的views.py文件:

from django.contrib.auth.views import LoginView


class CustomLoginView(LoginView):
    template_name = "blog/loginview.html"

这是我的urls.py文件:

from django.contrib.auth.views import LoginView
from django.conf.urls import url


urlpattenrs = [
   url(r'^login/$', views.CustomLoginView.as_view(), name='login')
]

我知道我可以把所有的东西都放在url中,而不必做我自己的视图,但我想测试一下

这是我的模板:

<h1>Connection with LoginView</h1>

<form method="POST" action=".">
    {% csrf_token %}
    {{ form.as_p }}

    <input type="hidden" name="next" value="{{ next }}" /> 
    <input type="submit" value="Connect" />
</form>

一切都很完美,但在我的页面上,我可以看到AuthenticationForm默认使用的LoginView的默认标签。 它们是Username:Password:

下面是我的问题:

  • 是否可以将模板中的标签更改为foo而不是Username:bar而不是Password:,并将{{ form.as_p }}保留在模板中?或者更好,从CustomLoginView更改标签

  • 是否可以为CustomLoginView使用自定义表单?或者更好,直接在LoginView中

谢谢你的帮助

更新:

根据Regnald Terry(https://stackoverflow.com/a/61033596/10830699)的回答,以下是我试图做的事情:

在我的forms.py中,我创建了这个:

from django.contrib.auth.forms import AuthenticationForm


class CustomAuthenticationForm(AuthenticationForm):
    class Meta:
        form = AuthenticationForm
        fields = "__all__"
        labels = {
            "username": "foo",
            "password": "bar"
        }

在yviews.py文件中:

from django.contrib.auth.views import LoginView

from .forms import CustomAuthenticationForm


class CustomLoginView(LoginView):
    template_name = "blog/loginview.html"
    authentication_form = CustomAuthenticationForm

这仍然不起作用。我做错了吗


Tags: 文件djangonamefrompyimportformauth