Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add styling to form.as_div in Django

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

{{ 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading