2

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?

1
  • it would be much easier to do it with javascript if you want all of them to share the same class Commented Feb 14, 2023 at 10:48

2 Answers 2

4

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):
   ...
Sign up to request clarification or add additional context in comments.

2 Comments

I am learning now django/python, so I don't understand, isn't BaseForm a "default" class included in django? So you suggest to override BaseForm?
Call it whatever you like; I've updated the name. The point is that you inherit from that rather than the basic ModelForm.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.