I want to specify the ** class attribute ** that is set in the ** html tag ** when I write the form to be displayed in the template with ** forms.py **.
forms.py
class Form(forms.Form):
sample = forms.IntegerField(label="hoge")
If this is left as it is, the output will be as follows, and the ** class attribute ** cannot be set in the ** input ** tag.
<input type="number" name="sample" required="" id="id_sample">
Override the ** \ _ \ _ init \ _ \ _ ** methods in ** forms.py **.
forms.py
class Form(forms.Form):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['sample'].widget.attrs['class'] = 'name of the class'
sample = forms.IntegerField(label="hoge")
There are two points to note.
Use this when you want to adjust the appearance with ** css ** when you define a form with ** forms.py **.
stackoverflow question https://stackoverflow.com/questions/401025/define-css-class-in-django-forms
Referenced answer https://stackoverflow.com/a/401057
Questioner https://stackoverflow.com/users/22306/ashchristopher
Respondent https://stackoverflow.com/users/22306/ashchristopher
Recommended Posts