Reputation: 532
I'm using a bootstrap modal to allow firefighter to update their status in an app I'm working on. The modal has buttons that make a POST request when clicked. csrf tokens are disabled for testing purposes
models.py
class Firefighter(models.Model):
STATUS_OPTIONS = (
('AV', 'Available'),
('OD', 'On Duty'),
('UN', 'Unavailable'),
('LV', 'Leave'),
)
first_name = models.CharField("First Name", max_length = 200)
last_name = models.CharField("Last Name", max_length = 200)
status = models.CharField("Status", max_length = 20 , choices=STATUS_OPTIONS, default='Available')
views.py
def updateStatus(request, id):
from django.http import JsonResponse
if request.method=='POST' and request.is_ajax():
try:
obj = Firefighter.objects.get(id=id)
obj.data_attr = request.POST['status']
obj.save()
return JsonResponse({'status':'Record Saved'})
except Firefighter.DoesNotExist:
return JsonResponse({'status':'Record does not exist'})
else:
return JsonResponse({'status':'Invalid POST request'})
Returns the Record Saved
JSON response when run.
urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^status/$', views.status, name='status'),
url(r'^status/update/(?P<id>\d+)/$', views.updateStatus, name='update'),
button jQuery
$('#btnAvailable').on('click', function() {
// You gotta include the csrf_token in your post data
$.post(`/status/update/${clickedID}/`, {'status': 'AV'}, function() {
$('#change-status').modal('hide');
location.reload(true)
});
});
Everything runs as it should, chrome shows no console errors for the POST request and yet the status
does not save on the DB. For example /status/update/22/
has their status currently set to UN
(Unavailable) the post request should set their status to AV
(Available) however the status never changes on the DB.
Upvotes: 1
Views: 816
Reputation: 4516
From what I'm seeing, you're not setting status
at all, your changing an attribute called data_attr (attaching it on runtime) and then calling save, which results in nothing saved in the DB, as expected.
Just change your data_attr
to status
and you're good to go
def updateStatus(request, id):
from django.http import JsonResponse
if request.method=='POST' and request.is_ajax():
try:
obj = Firefighter.objects.get(id=id)
obj.status = request.POST['status']
obj.save()
return JsonResponse({'status':'Record Saved'})
except Firefighter.DoesNotExist:
return JsonResponse({'status':'Record does not exist'})
else:
return JsonResponse({'status':'Invalid POST request'})
Also you have "Available" as default for your status, while your choices are otherwise (AV, OD, ...).
This should also be fixed, something like
STATUS_AVAILABLE = 'AV'
STATUS_ON_DUTY = 'OD'
STATUS_UN_AVAILABLE = 'UV'
STATUS_ON_LEAVE = 'OL'
STATUS_OPTIONS = (
(STATUS_AVAILABLE, 'Available'),
(STATUS_ON_DUTY, 'On Duty'),
(STATUS_UN_AVAILABLE, 'Unavailable'),
(STATUS_ON_LEAVE, 'Leave'),
)
status = models.CharField(..., choices=STATUS_OPTIONS, default=STATUS_AVAILABLE)
Upvotes: 2