我在Django中有一个评论表单,在提交评论之后,这个模式弹出窗口显示了一些文本,但它只出现了几秒钟,直到页面重定向。但我希望模态在那里,直到我手动点击"交叉"按钮(或模式框外的任何位置),然后页面应重定向到指定的位置。
views.py:
def add_comment_to_project(request,pk):
post = get_object_or_404(Project, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect('project_detail', pk=pk) //here it redirects.
else:
form=CommentForm()
return render(request, 'portfolio/add_comment_to_project.html', {'form':form})
add_comment_to_project.html:
{% extends 'portfolio/base.html' %}
{% block content %}
<h1>New Comment</h1>
<form method="POST" class="project-form">
{% csrf_token %}
{{ form.as_p }}
<button id="myBtn" type="submit" class="save btn btn-default">Send</button>
</form>
<!-- the Modal (prompt after clicking the send button) -->
<div id="mymodal" class="modal">
<!-- Modal Content -->
<div class="modal-content">
<span class="close">×</span>
<p>Thank you for your response ! :).<br>It has been recorded. It will be displayed once it has been approved by the author.</p>
</div>
</div>
{% endblock %}
的javascript:
// Get the modal
var modal = document.getElementById('mymodal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block"; //as initially, the display is none.
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
event.preventdefault();
/*window.location.reload();*/
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
我经常搜索相同的内容,但无法找到如何在Django中实现此目的的相关答案。
我希望将其重定向到&#34; Project_detail.html&#34;仅在手动关闭模态后,而不是仅在提交注释后直接关闭。请帮忙。非常感谢提前。
答案 0 :(得分:1)
而不是提交按钮:
<button id="myBtn" type="submit" class="save btn btn-default">Send</button>
你应该实现一个只触发模态窗口的按钮或链接:
<a class="send_comment">Send comment</a>
之后在js中你应该弹出模态并在点击模态中的关闭按钮时发送帖子:
function send_comment_modal() {
$(".send_comment").click(function() {
$('.modal')
.modal('show')
;
});
$('.modal .submit').click(function() {
$.post(window.location.href, temp, function(result){
if(result.success == 'ok') {
return;
}
})
});
}
我没有测试代码,但我认为你可以在我的代码片段后面得到这个想法!