Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How can I make forms in modals with Django CBVs?

I'm still newer to Django and have been trying to find a good tutorial for creating forms for CRUD operations inside of Bootstrap modals with Django. It seems like all the tutorials I've tried don't really work for me. Has anyone had any luck doing this or know of some good references for how to do this? Thanks

Jillian S. Estrella (she/her)
Jillian S. Estrella (she/her)
15,720 Points

It is just some HTML templating. No Django magic needs to happen aside from instantiating the form per the usual approach.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form method="POST">
        {% csrf_token %}
        {% form.as_p %}
        <input type="submit">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

1 Answer

Thanks Jonathan, I want to open the modal in a listview though, that would be great if i could just put the modal form right in the listview and have that be some kind of frankenview like a listview/createview but im not sure how that works. Also not sure how form/validation errors would work without some ajax. I wouldnt want the page to reload upon submission, id want the form/validation errors to show in the modal form without closing or submitting