A way to show Django detail view in a Bootstrap modal

wenx | Nov. 6, 2022, 6:34 p.m.

When building this website's 'publication' page, I used bootstrap and wanted to display a list of items that open a modal when clicking on it instead of opening up a new page. I got a solution from Stack overflow
https://stackoverflow.com/questions/72271709/django-detail-view-on-boostrap-modal
and an excellent article on how to realize it in detail from Medium
https://medium.com/@antoinewg/simple-modal-to-open-details-of-an-item-django-bootstrap-ffeeb11f12c1

After doing some trial and error by myself, i found a more straightforward way to implement the ideal. Here comes my solution:

I will use this website's 'publication' page as an example. I have a list of a few tens of publications in the form of a Bootstrap card, and when I click the 'read more' button on each publication card, I want to show the complete abstract and a link to that specific paper in a Bootstrap modal.
{% for publication in publication_list %}

#in the card body i have the button below to trigger modal for showing the detail.
<a href="" class="btn btn-outline-info" data-bs-toggle="modal" 
data-bs-target="#pubmodal{{ publication.number }}">Read More&rarr;</a> 


Here i used a dynamic target name for the modal, "#pubmodal{{ publication.number }}".

So within the for loop for publication_list, I made a 'div' that holds the hidden modal:

<div class="modal fade" id="pubmodal{{ publication.number }}" tabindex="-1"
    aria-labelledby="pubmodalLabel{{ publication.number }}" aria-hidden="true">
# ... some modal title, modal body need to be included here based on your need.


The modal has a dynamic 'id' corresponding to the 'data-bs-target' in the button above. After that, I close the for loop: {% endfor %}

By doing this, I could show the detail of a list in a modal for each element. I hope this could be useful if you wish to do something similar. Please let me know if you have any problems implementing the method.

About Me

Wen Xing

Research Scientist

I work as research scientist in the group of Thin Film and Membrane Technology, department of Sustainable Energy @ SINTEF

I speak Chinese, English and some Norwegian.