I'm learning Django 3.0 and I'm actually using the django.contrib.auth.views.LoginView

Here is my views.py file:

from django.contrib.auth.views import LoginView

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

And here is my urls.py file:

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

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

I know I could put everything in the url without making my own view but I wanted to test it.

Here is my template:

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

Everything works perfectly, but on my page, I can see the default labels from the AuthenticationForm used by default by the LoginView. These are Username: and Password:.

Now here are my questions:

  • Is it possible to change the labels to foo instead of Username: and bar instead of Password: from the template and keep the {{ form.as_p }} in the template? Or even better, changing the labels from the CustomLoginView?

  • Is it possible to use a custom form for the CustomLoginView? Or even better, directly in the LoginView?

2

There are 2 best solutions below

1
Regnald Terry On BEST ANSWER

Yes it is possible to change the labels but it will be in forms.py file, here is an example:

class ChildForm(forms.ModelForm):
    class Meta:
        model=Child_detail
        fields="__all__"
        labels={
            'username':'foo',
            'passowrd':'bar',
        }
0
BKSalman On

I overwritten the AuthenticationForm and used it in the overwritten LoginView:

forms.py

from django.contrib.auth.forms import AuthenticationForm

class CustomAuthenticationForm(AuthenticationForm):
    def __init__(self, request=None, *args, **kwargs):
        super().__init__(request=None, *args, **kwargs)
        self.fields['username'].label = 'a cool label'
        self.fields['password'].label = 'another cool label'

views.py

from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name = "login.html"
    authentication_form = CustomAuthenticationForm

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', MyLoginView.as_view(template_name= 'login.html'), name='login'),
]