Hi all. I’d like to trigger a delete operation using the browser’s window.confirm
. Showing a dedicated ‘delete_confirm.html’ page would be simple but I’m interested in how to do this window.confirm
approach so would love to learn some solutions.
Here’s my view code:
def delete_opportunity(request, opportunity_id):
"""View function to delete an opportunity"""
opportunity = get_object_or_404(Opportunity, pk=opportunity_id)
if request.method == "POST":
project_id = opportunity.project.id
opportunity.delete()
messages.success(request, "Opportunity deleted")
return redirect("monitor:project_detail", project_id=project_id)
return JsonResponse(
{
"success": True,
"redirect_url": reverse(
"monitor:project_detail", kwargs={"project_id": opportunity.project.id}
),
}
)
Here’s the url:
path(
"opportunity/<int:opportunity_id>/delete",
views.delete_opportunity,
name="delete_opportunity",
),
Here’s the html and stub js that shows the delete operation:
<div>
<a href="{% url 'monitor:project_detail' project_id=opportunity.project.id %}">Back to project</a>
<button id="delete-opportunity" class="contrast">
Delete opportunity
</button>
</div>
<script>
const showButton = document.getElementById('delete-opportunity');
showButton.addEventListener("click", () => {
window.confirm("Are you sure you want to delete this opportunity?")
});
</script>
Thank you in advance.