Bob Rob
Bob Rob

Reputation: 174

How can I add a class attribute to all my forms widgets automatically in Django?

I would like that every time I create a form with django the tag input includes a specific css class (form-control), to do this I have to write in form.py the following code, adding lines for each field:

class InsertItem(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'form-control'})
        self.fields['price'].widget.attrs.update({'class': 'form-control'})

Is there a way to force Django to include the css class that I need in every form, without having to write that things for each from and each line?

Upvotes: 2

Views: 1699

Answers (2)

linizio
linizio

Reputation: 185

I am using django-widget-tweaks application to add class attribute.

  1. install application
  2. create form just modelForm
class InsertItem(forms.ModelForm):
    class Meta:
        model = modelName
  1. use application in template code
{% load widget_tweaks %}

<form method="post">
{% csrf_token %}
{% for field in form %}
    {% render_field field class="form-control" %}
{% endfor %}
</form>

{% load widget_tweaks %} : load application to use it

{% render_field : command
field : field name to add class
class="form-control" %} : attribute

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599778

Write a common base class that updates every field:

class StylishForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs.update({'class': 'form-control'})

and inherit from it:

class InsertItem(StylishForm):
   ...

Upvotes: 4

Related Questions