How to load content dynamically from database into Bootstrap modal using Django

Viewed 205

I am working on a testing app that lists out users from the database in a HTML table, what I want to achieve is this, when you click on any icon for a particular record or row the full detail of that record is displayed in a Bootstrap Modal. My problem is how do I implement my views, urls, and also my Templates? Do I need Javascript help here? Cause in PHP this is done easily without JavaScript. Plesae I will prefer code samples as a correction to my issue thanks.

Here is my view

def users(request):
    get_users = User.objects.all()
    return render(request, 'classwork_app/users.html', {'users':get_users})

My urls

from classwork_app import views

app_name = 'classwork_app'

urlpatterns = [
    path('', views.users, name='users'),
]

Templates

<table class="table table-bordered">
            <tr>
              <th>S/N</th>
              <th>Username</th>
              <th>Firstname</th>
              <th>Lastname</th>
              <th colspan="2">Action</th>
            </tr>

            {% if users %}
              {% for u in users %}
                <tr>
                  <td>{{ forloop.counter }}</td>
                  <td>{{ u.username }}</td>
                  <td>{{ u.first_name }}</td>
                  <td>{{ u.last_name }}</td>
                  <td style="font-size: 12px"><a data-toggle="modal"  href="#MyModal{{ u.id }}"><i class="fa fa-eye"></i></a></td>
                </tr>
              {% endfor %}
            {% endif %}

          </table>

          <div id="#MyModal{{ u.id }}" class="modal fade" role="dialog">
            <div class="modal-dialog">

              <!-- Modal content-->
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal">&times;</button>
                  <h4 class="modal-title">{{ u.first_name }} {{ u.last_name }}</h4>
                </div>
                <div class="modal-body">
                  <p>
                    Username: {{ u.username }}
                    Firstname: {{ u.first_name }}
                    Lastname: {{ u.last_name }}
                  </p>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
              </div>

            </div>
          </div>
1 Answers

you can try putting your modal html code inside the for user iterator. This way it will load a modal with user content for every user in your list (not very recommended if you have a lot of data, can cause performance issues)

Related