Django adding placeholders to django built in login forms

后端 未结 5 594
灰色年华
灰色年华 2021-01-06 03:13

I\'m using django built-in login forms and i want to add placeholders to username and password.

My template:

<
5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-06 03:52

    save this content in forms.py

    from django import forms
    from django.contrib.auth.forms import AuthenticationForm
    from django.forms.widgets import PasswordInput, TextInput
    
    
    class MyAuthForm(AuthenticationForm):
        class Meta:
            model = User
            fields = ['username','password']
        def __init__(self, *args, **kwargs):
            super(MyAuthForm, self).__init__(*args, **kwargs)
            self.fields['username'].widget = forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})
            self.fields['username'].label = False
            self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Password'}) 
            self.fields['password'].label = False
    

    and save this content in main urls.py

    from users.forms import MyAuthForm
    
    urlpatterns = [
       ...
       path('', auth_views.LoginView.as_view(template_name='users/login.html', authentication_form=MyAuthForm), name='login'),
       ...
    ]
    

    please refer this site: https://github.com/django/django/blob/master/django/contrib/auth/views.py

提交回复
热议问题