2017-10-07 148 views
0

我正在django的一個項目中工作。我有這部分代碼,當我想要刪除一個專輯時,它會顯示Yes或No來選擇,但問題是,無論我做出什麼選擇,它總是會刪除專輯。我知道我必須添加一些東西到確認選項,但我不想要在哪裏或什麼。在django中刪除確認

<form action="{% url 'music:delete_album' album.id %}" method="post" style="display: inline;"> 
           {% csrf_token %} 
           <input type="hidden" name="album_id" value="{{ album.id }}" /> 
           <button type="submit" onclick="confirm('Are you sure ?')" class="btn btn-default btn-sm"> 
            <span class="glyphicon glyphicon-trash"></span> 
           </button> 
          </form> 

,這是delete_album觀點:

def delete_album(request, album_id): 
    album = Album.objects.get(pk=album_id) 
    album.delete() 
    albums = Album.objects.filter(user=request.user) 
    return render(request, 'music/index.html', {'albums': albums}) 
+0

javascript confirm()方法返回一個布爾值。只有當它返回true時,你才應該提交表單。 – aris

+0

,我該怎麼做? –

+1

試試這個:從你現在的位置刪除confirm(),並把它放在表單中:

aris

回答

1

好,它可以被驗證之前提交表單。如果你複製下一個剪切然後它將驗證:)

<form action="{% url 'music:delete_album' album.id %}" 
    method="post" style="display: inline;" onsubmit="window.mytest()"> 
    {% csrf_token %} 
    <input type="hidden" name="album_id" 
     value="{{ album.id }}" /> 
    <button type="submit" class="btn btn-default btn-sm"> 
     <span class="glyphicon glyphicon-trash"></span> 
    </button> 
</form> 
<script type="text/javascript">window.mytest = function() { var isValid = confirm('Are you sure ?');if (!isValid) { event.preventDefault(); alert("It wont delete. Yay!");}}</script>