有没有办法向用户名字段添加样式 - django 表单,我尝试使用 self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'})
但它不起作用为什么
class UserForm(forms.ModelForm):
password = forms.CharField(required=True,label=' pass',widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':' pass ','style': 'font-size:24px;text-align: center;'}))
first_name = forms.CharField(required=True,label=' first name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' first name ','style': 'font-size:24px;text-align: center;'}) )
last_name= forms.CharField(required=True,label=' 2nd name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' 2nd name ','style': 'font-size:24px;text-align: center;'}) )
email= forms.EmailField(required=True,label=' email ',widget=forms.EmailInput(attrs={'class': 'form-control','placeholder':' email ... youremail@email.com','style': 'font-size:24px;text-align: center;'}) )
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('username','first_name','last_name','email','password')
def __init__(self, *args, **kwargs):
super(UserForm,self).__init__(*args,**kwargs)
self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'})
答案 0 :(得分:1)
您正在覆盖 Meta
类的构造函数。与 Form
不同,因此您应该在以下位置实现它:
class UserForm(forms.ModelForm):
password = forms.CharField(required=True,label=' pass',widget=forms.PasswordInput(attrs={'class': 'form-control','placeholder':' pass ','style': 'font-size:24px;text-align: center;'}))
first_name = forms.CharField(required=True,label=' first name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' first name ','style': 'font-size:24px;text-align: center;'}) )
last_name= forms.CharField(required=True,label=' 2nd name ',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' 2nd name ','style': 'font-size:24px;text-align: center;'}) )
email= forms.EmailField(required=True,label=' email ',widget=forms.EmailInput(attrs={'class': 'form-control','placeholder':' email ... youremail@email.com','style': 'font-size:24px;text-align: center;'}) )
# constructor of the UserForm, not Meta
def __init__(self, *args, **kwargs):
super().__init__(*args,**kwargs)
self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':'Username','style': 'font-size:24px;text-align: center;'})
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('username','first_name','last_name','email','password')