我正在使用引导模式来让消防员在我正在处理的应用中更新其状态。模态具有在单击时发出POST请求的按钮。 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'})
运行时返回Record Saved
JSON响应。
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'),
按钮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)
});
});
一切都按预期运行,chrome没有显示POST请求的控制台错误,但status
没有保存在数据库上。例如,/status/update/22/
的状态当前设置为UN
(不可用),请求后的请求应将其状态设置为AV
(可用),但状态永远不会在数据库中更改。
答案 0 :(得分:1)
从我所看到的情况来看,你根本没有设置status
,你改变了一个名为data_attr的属性(在运行时附加它),然后调用save,这导致数据库中没有保存,预期
只需将data_attr
更改为status
,就可以了
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'})
此外,您的状态默认为“可用”,否则您选择(AV,OD,...)。
这也应该修复,比如
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)