modal forms using django variables
Date: April 11th 2016
Last updated: April 11th 2016
I like modals (pop up window). Getting a modal to work with Django doesnt require anything special. However, there is one little trick that took me a while to figure out. The "trick" happens at the html button that opens the modal. Specifically, you need to provide a definition in the data-target.
In this example I have added "#" to the data-target which allowed me to access the board object inside the modal. I found the solution on stackoverflow (http://stackoverflow.com/questions/13168606/passing-value-to-bootstrap-modal-in-django).
views.py
@login_required
def profilepage(request, surfer_id):
surfer_profile = dict()
surfer = get_object_or_404(Surfer, pk=surfer_id)
boardstest = surfer.boards.all()
return render(request, 'surferprofile/profile.html',{'boardstest': boardstest})
HTML Template
<!-- add jquery and bootstrap CSS -->
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<!-- loop over boardstest and provide either an edit button or view button -->
{% for board in boardstest %}
{{board}}
{% if request.user.id == board.user.id %}
<!-- provide an edit button -->
<a href="{% url 'surferprofile:editboard' surfer_id=surfer.id board_id=board.id %}"
style="color: blue; text-decoration: none;">edit</a>
{% else %}
<!-- Otherwise provide a view button -->
<p><button style="width: 50px;" type="button"
class="btn btn-primary" data-toggle="modal"
data-target="#{{board.pk}}"> view </button></p>
<div id="{{board.pk}}" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<p> <h2>Board specs</h2><br>
<h4>{{board.boardmake}}</h4><br>
</p>
</div>
</div>
</div>
</div>
{% endif %}
</p>
{% endfor %}
<!-- add to the bottom of the HTML template (just above </body> tag) -->
<script>
function centerModal() {
$(this).css('display', 'block');
var $dialog = $(this).find(".modal-dialog");
var offset = ($(window).height() - $dialog.height()) / 2;
// Center modal vertically in window
$dialog.css("margin-top", offset);
}
$('.modal').on('show.bs.modal', centerModal);
$(window).on("resize", function () {
$('.modal:visible').each(centerModal);
});
</script>
</body>