A
A
awd102017-02-28 19:12:32
Django
awd10, 2017-02-28 19:12:32

How to override form style in django?

1. How can I override the template so that only my own version is used by default when called {{form}}, without adding .as_div every time in the template?
2. How to add a CSS class to the wrapper html_class_attr? (except for the option to add to the stupid class="myclass" in normal_row)
forms.py

class BaseForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ModelForm, self).__init__(*args, **kwargs)
        # adding css classes to widgets without define the fields:
        for field in self.fields:
            self.fields[field].widget.attrs['class'] = 'form-input'

    def as_div(self):
        return self._html_output(
            normal_row=u'<div%(html_class_attr)s>%(label)s %(field)s %(help_text)s %(errors)s</div>',
            error_row=u'<div class="error">%s</div>',
            row_ender='</div>',
            help_text_html=u'<div class="hefp-text">%s</div>',
            errors_on_separate_row=False)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
javedimka, 2017-03-01
@awd10

To change the form's default rendering style to your own, you can override the form's __str__() method:

def __str__(self):
    return self.as_div()

The second question is kind of not very good.
html_class_attr is a string that is generated in the _html_output() method based on some data, I don’t know what, I need to dig deeper into the sorts, they don’t write this in the docks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question