2017-01-12 21 views
1

我有一個評論的形式在Django和submiting評論後,有一個顯示一些文字此模式彈出,但直到頁面重定向幾秒鐘只能出現之後。但我想的模式在那裏,直到我手動點擊「十字架」按鈕(或模態對話框以外的任何位置),然後根據指定的頁面應該重定向到的位置。Django的 - 重定向僅關閉JavaScript的模態手動

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」的模式被手動關閉後才能,並提交評論後,不只是直接。請幫忙。提前致謝。

回答

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

我沒有測試的代碼,但我TH墨水,你可以得到我的代碼片段背後的想法!

+0

我明白你的代碼背後的邏輯,但由於其在jQuery的你片斷,和我沒有太多熟悉的話,你可以請你的評論片段,並解釋究竟什麼發生?主要是從'$ .post(window ...)'開始的第二部分。感謝 –

+0

爲我寫的,當你點擊鏈接模態窗口彈出。當你點擊模式窗口中的按鈕時,它會發送發佈請求。但是,我的代碼片段不包含上下文(臨時變量),您應該也可以通過post請求傳遞該上下文(temp變量)。 –