I'll help you create a polished CRUD interface with proper styling. Let's assume you're using Django and have a model already defined. Here's a step-by-step enhancement:
Base Template (base.html) - Include Bootstrap for styling:
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib import messages
from .models import Item # Replace with your model
from .forms import ItemForm # Replace with your form
class ItemListView(ListView):
model = Item
template_name = 'item_list.html'
context_object_name = 'object_list'
class ItemCreateView(CreateView):
model = Item
form_class = ItemForm
template_name = 'item_form.html'
success_url = reverse_lazy('item-list')
def form_valid(self, form):
messages.success(self.request, 'Item created successfully!')
return super().form_valid(form)
class ItemUpdateView(UpdateView):
model = Item
form_class = ItemForm
template_name = 'item_form.html'
success_url = reverse_lazy('item-list')
def form_valid(self, form):
messages.success(self.request, 'Item updated successfully!')
return super().form_valid(form)
class ItemDeleteView(DeleteView):
model = Item
template_name = 'item_confirm_delete.html'
success_url = reverse_lazy('item-list')
def form_valid(self, form):
messages.success(self.request, 'Item deleted successfully!')
return super().form_valid(form)
Add this to your forms.py:
python
from django import forms
from .models import Item
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = ['name', 'description'] # Update with your fields
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs.update({'class': 'form-control'})
Key features included:
Responsive design with Bootstrap 5
Card-based layout with shadows
Hover effects on tables
Success/error messages
Form error handling
Confirmation for delete operations
Consistent styling across all pages
Proper spacing and alignment
Make sure to:
Replace Item with your actual model name
Update form fields according to your model
Set up proper URL patterns
Add your static files configuration
Create appropriate messages for different operations
Test all CRUD operations thoroughly
For even better styling, you can:
Add custom CSS in a separate static file
Include icons using Bootstrap Icons
Add pagination to the list view
Implement search functionality
Add client-side form validation
Use modals for delete confirmation instead of separate page
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:
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.
Here's how to implement optimistic locking in your Django application to prevent concurrent update conflicts using version control. This approach ensures users can't overwrite each other's changes:
1. Add Version Field to Model
python
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
version = models.PositiveIntegerField(default=0)
def save(self, *args, **kwargs):
# Increment version on each save
self.version += 1
super().save(*args, **kwargs)
2. Update Form to Include Version Field
python
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = ['name', 'description', 'version'] # Add version
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['version'].widget = forms.HiddenInput()
3. Modify Update View for Version Checking
python
from django.http import JsonResponse
from django.core.exceptions import ValidationError
class ItemUpdateView(UpdateView):
model = Item
form_class = ItemForm
def form_valid(self, form):
try:
# Check version conflict
current_version = form.cleaned_data['version']
db_version = self.get_object().version
if current_version != db_version:
raise ValidationError("This record has been modified by another user. Please refresh and try again.")
return super().form_valid(form)
except ValidationError as e:
if self.request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return JsonResponse({
'success': False,
'errors': {'__all__': [str(e)]}
}, status=409)
return super().form_invalid(form)
4. Frontend Handling
Update your JavaScript to handle version conflicts:
javascript
$(document).on('submit', '#itemForm', function(e) {
e.preventDefault();
const $form = $(this);
const originalVersion = $form.find('#id_version').val();
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(response) {
if(response.success) {
$('#crudModal').modal('hide');
loadItems();
}
},
error: function(xhr) {
if(xhr.status === 409) {
// Version conflict - show resolution modal
showConflictModal(xhr.responseJSON.errors.__all__[0]);
} else {
$('#modal-body').html(xhr.responseText);
}
}
});
});
function showConflictModal(message) {
const conflictModal = `
<div class="modal fade" id="conflictModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-warning">
<h5 class="modal-title">Conflict Detected</h5>
</div>
<div class="modal-body">
<p>${message}</p>
<button onclick="loadCurrentVersion()" class="btn btn-primary">
Load Latest Version
</button>
</div>
</div>
</div>
</div>`;
$(conflictModal).modal('show');
}
function loadCurrentVersion() {
$('#conflictModal').modal('hide');
$('#crudModal').modal('hide');
loadItems(); // Refresh the list
// Optionally: Re-open the form with latest data
}
5. Add Version to List Display
Update your table template to include version numbers:
Version Tracking: Each save increments the version number
Conflict Detection: During updates, compares submitted version with current DB version
Conflict Resolution:
Returns 409 Conflict status for AJAX requests
Shows user a conflict resolution modal
Allows reloading of current version
Additional Enhancements:
Audit Trail:
python
class ItemAudit(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
version = models.PositiveIntegerField()
data = models.JSONField()
modified_by = models.ForeignKey(User, on_delete=models.SET_NULL)
modified_at = models.DateTimeField(auto_now_add=True)
Client-Side Version Lock:
javascript
let currentEditVersion = null;
function openEditModal(itemId) {
$.get(`/items/${itemId}/`, function(data) {
currentEditVersion = data.version;
// Populate form fields
});
}
Server-Side Optimistic Lock Middleware:
python
class OptimisticLockMiddleware:
def process_view(self, request, view_func, view_args, view_kwargs):
if request.method in ['PUT', 'PATCH', 'POST']:
model = getattr(view, 'model', None)
if model and hasattr(model, 'version'):
# Add version checking logic here
pass
Testing Considerations:
Simulate concurrent edits using multiple browser windows