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

在Django中实现Ajax请求成功后启用提交按钮并修改按钮值

Solution for AWS-Like Lab Creation Workflow in Django

I’ve built similar AWS-style environment provisioning flows before, so here’s a practical implementation that checks all your boxes:

1. HTML Template Setup

First, structure your form with unique IDs for easy JavaScript targeting, plus a modal for status prompts:

<form id="lab-creation-form" method="POST">
    {% csrf_token %}
    <div class="form-group">
        <label for="lab-name">Lab Name</label>
        <input type="text" id="lab-name" name="lab_name" required>
    </div>
    <div class="form-group">
        <label for="cidr-block">CIDR Block</label>
        <input type="text" id="cidr-block" name="cidr_block" placeholder="e.g., 10.0.0.0/16" required>
    </div>
    <button type="submit" id="create-lab-btn" class="btn btn-primary">CREATE LAB</button>
</form>

<!-- Status Modal -->
<div class="modal fade" id="status-modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modal-title"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="modal-body"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

2. Django View for Ajax Endpoint

Create a view that handles lab creation logic and returns JSON responses (decorate it to enforce POST requests):

from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import LabEnvironment  # Adjust to your model

@require_POST
def create_lab(request):
    try:
        lab_name = request.POST.get('lab_name')
        cidr_block = request.POST.get('cidr_block')
        
        # Add your core lab creation logic here (AWS API calls, DB saves, etc.)
        lab = LabEnvironment.objects.create(
            name=lab_name,
            cidr_block=cidr_block,
            status='CREATING'
        )
        
        # For async workflows (e.g., Celery + AWS), return success immediately
        # For sync workflows, wait until provisioning completes before responding
        
        return JsonResponse({
            'success': True,
            'message': f"Lab '{lab_name}' is being provisioned successfully!"
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': f"Failed to create lab: {str(e)}"
        }, status=400)

Add this view to your urls.py:

from django.urls import path
from .views import create_lab

urlpatterns = [
    # ... other URLs
    path('create-lab/', create_lab, name='create_lab'),
]

3. JavaScript Logic (jQuery for Simplicity)

Add this script to your template (or a dedicated JS file) to manage button state, Ajax calls, and post-success actions:

$(document).ready(function() {
    const createBtn = $('#create-lab-btn');
    const form = $('#lab-creation-form');
    const modal = $('#status-modal');
    
    form.submit(function(e) {
        e.preventDefault();
        
        // Lock button to prevent duplicates
        createBtn.prop('disabled', true);
        createBtn.text('CREATING');
        
        // Prepare form data
        const formData = new FormData(this);
        
        // Send Ajax request
        $.ajax({
            url: '{% url "create_lab" %}',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                // Update button for success
                createBtn.prop('disabled', false);
                createBtn.text('CREATED');
                createBtn.addClass('btn-success');
                
                // Show success prompt
                $('#modal-title').text('Success!');
                $('#modal-body').text(response.message);
                modal.modal('show');
                
                // Refresh page after 1 minute
                setTimeout(function() {
                    window.location.reload();
                }, 60000);
            },
            error: function(xhr) {
                // Reset button on failure
                createBtn.prop('disabled', false);
                createBtn.text('CREATE LAB');
                
                // Show error prompt
                const errorMsg = xhr.responseJSON?.message || 'An unknown error occurred.';
                $('#modal-title').text('Error');
                $('#modal-body').text(errorMsg);
                modal.modal('show');
            }
        });
    });
});

Key Best Practices

  • CSRF Protection: The example uses Django’s built-in CSRF token via the form—if you’re not using jQuery, manually add the X-CSRFToken header to your Ajax request.
  • Async Workflows: For long-running AWS provisioning tasks, use Celery or AWS Step Functions to handle background work. The view can return success immediately, and you can use WebSockets/polling to update the UI once the lab is ready.
  • UX Improvements: Add a loading spinner next to the "CREATING" text to make the active state clearer.
  • Input Validation: Add frontend checks for valid CIDR formats and backend validation to avoid invalid data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:42:56