Here's how to implement AJAX-based CRUD operations with your existing setup using jQuery (included in Bootstrap 5) and Django's JSON response capabilities:
1. First, Update Your Base Template (base.html)
Add jQuery and a JavaScript block:
<!-- Add after Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Initialize CSRF token for AJAX requests
$.ajaxSetup({
headers: {
"X-CSRFToken": "{{ csrf_token }}"
}
});
});
</script>
{% block javascript %}{% endblock %}
2. Modify Views to Handle AJAX Requests
Update your views to return JSON responses for AJAX requests:
from django.http import JsonResponse
from django.template.loader import render_to_string
class ItemListView(ListView):
model = Item
template_name = 'item_list.html'
def get(self, request, *args, **kwargs):
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
items = list(self.get_queryset().values())
return JsonResponse(items, safe=False)
return super().get(request, *args, **kwargs)
class ItemCreateView(CreateView):
model = Item
form_class = ItemForm
def form_valid(self, form):
response = super().form_valid(form)
if self.request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return JsonResponse({
'success': True,
'message': 'Item created successfully!',
'item': {
'id': self.object.id,
'name': self.object.name,
'description': self.object.description
}
})
return response
def form_invalid(self, form):
if self.request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return JsonResponse({
'success': False,
'errors': form.errors
})
return super().form_invalid(form)
# Similarly modify UpdateView and DeleteView
3. Create a Modal for Forms
Add this to base.html:
<div class="modal fade" id="crudModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body" id="modal-body">
<!-- Form will be loaded here -->
</div>
</div>
</div>
</div>
4. Update List Template (item_list.html)
Modify the table and add JavaScript:
{% block javascript %}
<script>
$(document).ready(function() {
// Load initial items
loadItems();
// Create Button Handler
$('.create-btn').click(function() {
$.get("{% url 'item-create' %}", function(data) {
$('#crudModal .modal-title').text('Create Item');
$('#modal-body').html(data);
$('#crudModal').modal('show');
});
});
// Submit Form Handler
$(document).on('submit', '#itemForm', function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(response) {
if(response.success) {
$('#crudModal').modal('hide');
loadItems();
}
},
error: function(xhr) {
$('#modal-body').html(xhr.responseText);
}
});
});
// Delete Handler
$(document).on('click', '.delete-btn', function() {
if(confirm('Are you sure?')) {
$.ajax({
type: 'DELETE',
url: $(this).data('url'),
success: function() {
loadItems();
}
});
}
});
});
function loadItems() {
$.get("{% url 'item-list' %}", function(data) {
let html = '';
data.forEach(item => {
html += `
<tr>
<td>${item.name}</td>
<td>${item.description}</td>
<td>
<button class="btn btn-sm btn-warning edit-btn"
data-url="/update/${item.id}/">Edit</button>
<button class="btn btn-sm btn-danger delete-btn"
data-url="/delete/${item.id}/">Delete</button>
</td>
</tr>`;
});
$('#itemTable tbody').html(html);
});
}
</script>
{% endblock %}
5. Update URL Patterns
Make sure your URLs have names matching the AJAX calls:
urlpatterns = [
path('', ItemListView.as_view(), name='item-list'),
path('create/', ItemCreateView.as_view(), name='item-create'),
path('update/<int:pk>/', ItemUpdateView.as_view(), name='item-update'),
path('delete/<int:pk>/', ItemDeleteView.as_view(), name='item-delete'),
]
6. Create Partial Form Template (_form.html)
For AJAX form loading:
<form method="post" id="itemForm" action="{% if form.instance.id %}{% url 'item-update' form.instance.id %}{% else %}{% url 'item-create' %}{% endif %}">
{% csrf_token %}
<div class="mb-3">
{{ form.name.label_tag }}
{{ form.name }}
<div class="text-danger">{{ form.name.errors }}</div>
</div>
<div class="mb-3">
{{ form.description.label_tag }}
{{ form.description }}
<div class="text-danger">{{ form.description.errors }}</div>
</div>
<button type="submit" class="btn btn-success">Save</button>
</form>
Key Features:
- Full AJAX operations without page reloads
- Modal-based form handling
- Dynamic table updates
- Error handling with form validation
- CSRF token protection
- Bootstrap modal integration
- Progress indicators (you can add loading spinners)
To complete the implementation:
- Add similar AJAX handling for update operations
- Implement loading indicators
- Add error messages for failed operations
- Include proper status codes in your view responses
- Add client-side validation
- Implement proper error handling in AJAX calls
This implementation provides a modern, single-page-application-like experience while maintaining Django's form validation and security features.