Home > front end >  Add styling to form.as_div in Django
Add styling to form.as_div in Django

Time:09-07

I am rendering a model form in Django using {{ form.as_div }}

It is rendering as expected as I want each field wrapped in a div.

I would now like to add a class to this auto generated div.

adding widgets in the forms.py file only adds attribute to the input field itself and not the div around the field.

Can someone point me in the right direction to add attributes to the div instead of the input field?

Thank you

CodePudding user response:

{{ form.as_div }} is not possible in Django but, you can do like this

====== in views.py =========

def DemoView(request):
    form = StudentForm()
    context = {'form':form}
    return render(request,'demo.html',context)

======= in html file ========

<h1>Student Form</h1>
<form action="" method="get" >
    {% for fm in form %}
        <div>
            <label>{{fm.label}}</label>
            <p>{{fm}} </p>
        </div>
    {% endfor %}
</form>

======= Output =========

enter image description here

  • Related