Well, you haven’t put any code from your templates there - if you want a CSS class in form
of HTML, it is in the templates that you need to manually - the classes of django.forms
even has rendering methods for HTML, but the tag Form
always comes in the template - Python objects are rendered for text, help, and widgets that go within form.
Already if you want to add attributes class
custom controls (widgets) generated by Django form, that’s another conversation -
You can associate html classes to each control of a form by passing the parameter attrs
when creating the field - the documentation is here:
https://docs.djangoproject.com/en/2.2/ref/forms/widgets/#styling-widget-instances
Of course, as in this case, you are using a modelform, this would imply that you would have to declare the Fields manually in the class you inherit from ModelForm
, to pass the parameter attrs
for the widget.
If you want to keep everything automatic and change only the attrs, you can do this right after declaring the class, and manipulate the obejto Field
manually - the creation of Django form classes has a customization that makes them different from normal Python classes - the Fields
one-class django.forms.Form
are in dictionaries within the class, and not directly as class attributes - all are listed within a dictionary called base_fields
. On an object of the type Field
, you can directly access the attribute widget
and customize the attribute attrs
of the same (which is a Python dictionary) attrs
will be rendered to html:
class TransacaoForm(ModelForm):
class Meta:
model = Transacao
fields = ['dt_transaco','descricao','valor','categoria','observacoes']
field_descricao = TransacaoForm.base_fields["descricao"]
descricao.widget.attrs["class"] = "minha_classe_CSS"]
And ready, when using one of the methods to render this form, the field
"Description" will see with `class="my_classe_CSS" in its Input element.
If you want to change the Label and HTML class of what comes around Input too, in this case you will have to create your own widget class, and customize everything.
Thanks guy really worked!
– Mauricio Dantas