[Answered ]-Is it possible to customize the HTML generated for a django.forms.Form?


You can change the form using javascript by including the javascript files in your forms ‘Media’ inner class

class MyForm(form.ModelForm):

    class Media:
        # Paths relative to STATIC_URL
        js = ("js/file.js", "js/file2.js",)

But, in my opinion that can be a bit hacky

Alternatively, to change a specific field’s HTML you should create your own widget for the specific fields you want to edit:


Finally, if you need to dynamically add or remove fields, I think the best way you can do so is in your forms init function:

class MyForm(form.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        if self.fields['example_field_name'].initial == "some_value":
            # do something ...

Leave a comment