Django中的内置身份认证视图所使用的表单,比如LoginView的表单是无法添加样式的,试了很久,终于找到一个办法解决该问题:
1. 在forms.py中继承LoginView对应的表单AuthenticationForm:
from django.contrib.auth.forms import AuthenticationForm class MyAuthenticationForm(AuthenticationForm): def __init__(self, request, *args, **kwargs): super(AuthenticationForm, self).__init__(request.POST, *args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control'
或者
class MyAuthenticationForm(AuthenticationForm):
username = forms.CharField(required=True, widget=forms.TextInput(attrs={'class': 'form-control'}))
password = forms.CharField(required=True, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
2. 在url中定义链接:
from django.contrib.auth import views as auth_views
from .forms import MyAuthenticationForm
app_name = 'account'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='account/login.html',
authentication_form=MyAuthenticationForm)),
]
另外,如果有FormModel想要增加class:
class BaseForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BaseForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' class UserForm(BaseForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput) def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don"t math!') return cd['password2'] class Meta: model = User fields = ('username', 'first_name', 'last_name') class ProfileForm(BaseForm): class Meta: model = Profile fields = ('nick_name', 'phone_number')