我试图在我的表单上向<input>
添加一个类。按照this question的第一个回答的说明,我在表单的__init__
方法中添加了一些代码。但是我得到了标题中显示的错误。
forms.py
class SignupForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
def __init__(self, *args, **kwargs):
form = super(SignupForm, self).__init__(*args, **kwargs)
for visible in form.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name',)
答案 0 :(得分:1)
您收到错误,因为super()
调用返回None
。在__init__
方法中,您可以使用self
访问表单的属性。
def __init__(self, *args, **kwargs):
super(SignupForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
...