我正在构建一个 Django 应用程序,它有一个带有一堆开/关切换的主仪表板。我的目标是允许用户打开或关闭其设置,并将更改自动保存到数据库中。
所以我关注了this在我的 Django 应用程序中利用 Ajax 表单提交的教程,以便用户不必重新加载页面。我遇到的问题(我认为)是复选框值被作为“on”发布到我的 Django View ,而它们应该被发布为“True”。
我认为这是错误的原因,因为我在错误日志中看到了这一点:
Exception Type: IntegrityError at /update_usersettings/
Exception Value: dataplan_usersettings.normalize_person_name_proper may not be NULL
...
POST:
id_normalize_person_name_proper = u'on'
id_normalize_company_name_proper = u'on'
我现有的JavaScript和Django的views.py在这里:https://gist.github.com/joefusaro/25b6221536291c1ba0d1
更新: 我添加了相关的 Django 模板和表单代码 here 。并不是说我正在使用 widget_tweaks用于表单渲染。表单呈现如下:
<form action="/update_usersettings/" method="POST" id="usersettings_form">
<input checked="checked" class="bootstrap-switch-default" id="id_normalize_person_name_proper" name="bootstrap-switch" type="checkbox" />
<input checked="checked" class="bootstrap-switch-default" id="id_normalize_company_name_proper" name="bootstrap-switch" type="checkbox" />
<input type="submit" value="Post">
最终更新
感谢 Animesh 提供了一个很好的起点。这是所需的最终 Ajax 代码。 特别感谢Victor K. 感谢他帮助解决这个问题!
这是最终的 Ajax 代码:
$(function() {
// Submit post on submit
$('#usersettings_form').on('submit', function(event){
event.preventDefault();
console.log("Form submitted...") // sanity check
save_usersettings();
});
$('input[type="checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
$('#usersettings_form').submit();
});
// AJAX for posting.
function get_post_data() {
var data = {};
$('input:checkbox').each(function () {
var $this = $(this);
var id = $this.attr('id');
data[id.replace('id_', '')] = $this.is(':checked');
});
return data;
}
function save_usersettings() {
console.log("Saving user settings...") // sanity check
$.ajax({
url : "update_usersettings/", // the endpoint
type : "POST", // http method
data : get_post_data(),
// handle a successful response
success : function(json) {
console.log(json); // log the returned json to the console
// $("#talk").prepend("<li><strong>"+json.text+"</strong> - <em> "+json.author+"</em> - <span> "+json.created+
// "</span> - <a id='delete-post-"+json.postpk+"'>delete me</a></li>");
console.log("Successfully saved user settings."); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
// $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
// " <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
这是最终的views.py:
class UpdateUserSettings(LoginRequiredMixin, UpdateView):
model = UserSettings
form = UserSettingsForm
def post(self, request, *args, **kwargs):
if request.method=='POST':
response_data = {}
form = UserSettingsForm({})
us = UserSettings.objects.get(user=1)
VALUE_MAP = {
'false': False,
'true': True
}
for name, field in form.fields.items():
if isinstance(field, BooleanField):
if request.POST.get(name):
if request.POST[name] in VALUE_MAP.keys():
setattr(
us,
name,
VALUE_MAP[request.POST[name]]
)
us.save()
response_data['result'] = 'Update successful!'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
return HttpResponse(
json.dumps({"nothing to see": "this isn't happening"}),
content_type="application/json"
)
最佳答案
您可以在 View 内处理此问题。
CHECKBOX_MAPPING = {'on':True,
'off':False,}
class UpdateUserSettings(LoginRequiredMixin, View):
model = UserSettings
def post(self,request,*args,**kwargs):
normalize_person_name_proper = CHECKBOX_MAPPING.get(request.POST.get('normalize_person_name_proper'))
您可以对您应该从用户的复选框中收到的所有字段执行此操作。
此外,这里需要注意的一件事是,您不需要在基于类的通用 View 的 post 方法内使用 request.method=='POST'
检查。仅当请求为 POST 时才会调用该方法。您要查找的是 if request.is_ajax():
希望这有帮助。
关于javascript - 在发布到 Django View 之前将复选框 'on' 转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28823916/