Arash Hatami
Arash Hatami

Reputation: 5541

Customize Django Form Style

how can i customize Django forms and set class for them ? for example i have a text box with bootstrap class and custom font :

<input type="text" class="form-control myfont" value="{{ model1.field1 }}"/>

but original form field " {{ form1.form_field1 }} " is a simple textbox with no style . i try to use this code :

<input type="text" class="form-control myfont" value="{{ form1.form_field1 }}"/>

this code didn't work . do you have suggestions ??

enter image description here

Upvotes: 1

Views: 784

Answers (2)

If you want to inject extra attributes with the least resistance you can use django-tweaks.

Installation

 $ pip install django-widget-tweaks

Then add ‘widget_tweaks’ to INSTALLED_APPS.

https://pypi.python.org/pypi/django-widget-tweaks

template.html

{% load widget_tweaks %}
{% render_field form1.form_field1 class="form-control myfont" %}

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213193

You can add extra attributes to widgets in form's __init__ method. If you many such forms, then you can have one super class form:

class BootstrapForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(BootstrapForm, self).__init__(*args, **kwargs)
        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field:
                field.widget.attrs.update({
                    'class': "form-control myfont"
                })

And then have your other forms extend this one.

Upvotes: 2

Related Questions