解决django中内置身份认证表单无法自定义渲染的问题

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

 

转载于:https://www.cnblogs.com/darknoll/p/8432918.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值