我在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">&times;</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中实现此目标的相关答案。

我希望仅在手动关闭模式后才将其重定向到“ Project_detail.html”,而不仅仅是在提交注释后立即将其重定向到“ Project_detail.html”。请帮忙。非常感谢。

最佳答案

代替提交按钮:

<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;
                }
            })
        });
    }


我没有测试代码,但我想您可以在我的代码片段中得到启发!

关于javascript - Django-仅在手动关闭javascript模式后才重定向,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41619353/

10-16 19:53