You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中实现点击Dissolve按钮弹窗确认后删除数据功能

Got it, let's break this down into front-end and back-end steps to get your Dissolve button working exactly as you want:

Front-End Implementation (HTML/JS)

First, we'll add a custom confirmation modal (using Bootstrap since your button already uses Bootstrap classes) and wire up the click events:

  1. Update your Dissolve button to include a data-job-id attribute (so we know which job to delete) and an ID for easier JS targeting:
<button type="button" class="btn btn-primary" id="dissolveBtn" data-job-id="{{ job.id }}">Dissolve</button>

Replace {{ job.id }} with your template's variable for the job's unique ID.

  1. Add the confirmation modal HTML somewhere in your page (usually before the closing </body> tag):
<!-- Confirmation Modal -->
<div class="modal fade" id="confirmDissolveModal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Confirm Dissolve</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Are you sure you want to delete this field?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="confirmDeleteBtn">Okay</button>
      </div>
    </div>
  </div>
</div>
  1. Add the JavaScript logic to handle button clicks, modal display, and the delete request:
// Initialize elements and state
const dissolveBtn = document.getElementById('dissolveBtn');
const confirmModal = new bootstrap.Modal(document.getElementById('confirmDissolveModal'));
const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
let targetJobId = null;

// Open modal when Dissolve is clicked, store the job ID
dissolveBtn.addEventListener('click', () => {
  targetJobId = dissolveBtn.getAttribute('data-job-id');
  confirmModal.show();
});

// Handle Okay click: send delete request then go back
confirmDeleteBtn.addEventListener('click', () => {
  fetch(`/jobs/${targetJobId}/delete`, {
    method: 'DELETE',
    headers: {
      // Include CSRF token if you're using a framework like Django
      'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value
    }
  })
  .then(response => {
    if (response.ok) {
      // Success: go back to previous page
      window.history.back();
    } else {
      alert('Failed to delete the job. Please try again.');
    }
  })
  .catch(err => {
    console.error('Delete error:', err);
    alert('An unexpected error occurred.');
  });
  
  // Close the modal
  confirmModal.hide();
});

Note: If you aren't using Bootstrap, you can use the browser's native confirm() dialog for a simpler (but less styled) solution:

dissolveBtn.addEventListener('click', () => {
  const jobId = dissolveBtn.getAttribute('data-job-id');
  if (confirm('Are you sure you want to delete this field?')) {
    fetch(`/jobs/${jobId}/delete`, {
      method: 'DELETE',
      headers: { 'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value }
    })
    .then(response => response.ok && window.history.back());
  }
});
Back-End Implementation (module.py)

Now, add a view to handle the delete request and remove the job from your database. Assuming you're using Django (adjust based on your framework):

from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from .models import Job  # Import your Job model

def delete_job(request, job_id):
    if request.method == 'DELETE':
        # Get the job or return 404 if not found
        job = get_object_or_404(Job, id=job_id)
        job.delete()
        return JsonResponse({'status': 'success'}, status=200)
    # Reject non-DELETE requests
    return JsonResponse({'status': 'error'}, status=400)

Don't forget to add a corresponding route in your urls.py to map the delete endpoint:

from django.urls import path
from . import module

urlpatterns = [
    # ... your other routes
    path('jobs/<int:job_id>/delete/', module.delete_job, name='delete_job'),
]

That's it! When a user clicks Dissolve, they'll see the confirmation popup. Cancel closes the modal, while Okay triggers the delete action and sends them back to the previous page.

内容的提问来源于stack exchange,提问作者Nnighojk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:27:38