2

Suppose I have a form:

class MyForm(forms.Form):
    ...

and then in a view I construct it:

...
form = MyForm()
...

I would like to add a CSS class to the entire form, so that I can render it as something like this:

<form class="{{ form.CLASS }}" method="post">{% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

What is the proper way to achieve that (other than define a field "class")?

jazzblue
  • 2,411
  • 4
  • 38
  • 63

1 Answers1

1

I would create an attribute in your form, by override the __init__ method, like what I've done here: Override defaults attributes of a Django form :)

You can name the attribute class_name for example, and initialize your form by form = MyForm(class_name="myCssClass")

Community
  • 1
  • 1
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97