我正在研究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 :(得分: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>