Placeholders for Login


from . import views
from django.urls import path
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('', views.homepage, name='homepage'),
    path('register/', views.register, name="register"),
    path('login/',auth_views.LoginView.as_view(template_name="login.html"), name="login"),
    path('logout/', auth_views.LogoutView.as_view(next_page="homepage"), name="logout"),
]

I have a Login Form, considering I used the usercreationform, and the login form is built in, how would I add a placeholder for both the username and password?

The same way I would do with any other form.

from django import forms

class SomeForm(forms.Form):
  the_field = forms.CharField(widget=forms.widgets.TextInput(attrs={"placeholder": "my placeholder"}))

  # Or... on the init method
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields["the_field"].widget.attrs["placeholder"] = "my placeholder"

The key here is to find where the form is defined. I suggest that you look into the auth_views.LoginView definition, on most IDEs this is the F12 or Ctrl + Click. This will lead you to the following code.

Notice that the LoginView that you’re using, have both interesting attributes, form_class or authentication_form, I will use form_class on this example.
form_class is defined as AuthenticationForm and if you go to the definition, then you’ll find that this forms is defined as.

Notice that it has a username field. Let’s say I want to add a placeholder to this field, then I can use one of the methods that I’ve shown before. In this case, it’s easier to override the __init__ method, because we only want to override a single attribute. So I will define on a forms.py (or in the same directory, up to you) the new form, that will inherit from the AuthenticationForm

# forms.py
from django.contrib.auth import forms as auth_forms

class MyAuthenticationForm(auth_forms.AuthenticationForm):
  def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields["username"].widget.attrs["placeholder"] = "The placeholder"

Now we need to use tell the view to use this form. You have 2 options, you can:

  1. do a similar “form inheritance” approach with the view and override the form_class attribute on your view;
  2. pass the form_class on the as_view method

I will use the 2nd one, since it’s the shortest. Change this line:

With this:

from .forms import MyAuthenticationForm  # This assumes that you've created a forms.py before

urlpatterns = [
  # .... others remain the same
  path('login/',auth_views.LoginView.as_view(template_name="login.html", form_class=MyAuthenticationForm), name="login"),
]

Hope that helps.

1 Like