How to adjust the size of help_texts in Django form?
I'm trying to adjust the size of help_texts field of 'username'. I don't understand where should apply the styling.
class SignUpForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'}), label='')
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'}), label='')
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'phone']
widgets = {
'username': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Username'}),
'email': forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email Address'}),
'phone': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Phone Number'}),
}
labels = {
'username': '',
'email': '',
'phone': ''
}
help_texts = {
"username": "Must contain only letters, numbers, hyphens and underscores.",
}
You can overwrite help_text
. I used mark_safe
to render the string as html
from django.utils.safestring import mark_safe
class SignUpForm(UserCreationForm):
...
...
def __init__(self, *args, **kwargs):
super(SignUpForm, self).__init__(*args, **kwargs)
self.fields['username'].help_text = mark_safe(
'<span style="color: red; font-size: 12px;">'
f'{self.fields["username"].help_text}</span>'
)
You should do it in init method. I will give an example for the field, but you can change anything like this.
class SignUpForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
self.fields['username'].widget = forms.TextInput(
attrs={
'placeholder': 'Bla Bla',
'style': 'height:100px;',
'class': 'form-class',
}
)