gpt4 book ai didi

javascript - 在发布到 Django View 之前将复选框 'on' 转换为 bool 值

转载 作者:行者123 更新时间:2023-11-29 21:51:35 25 4
gpt4 key购买 nike

我正在构建一个 Django 应用程序,它有一个主仪表板和一堆开/关切换。我的目标是允许用户打开或关闭他们的设置,并将他们的更改自动保存到数据库中。

所以我关注了this在我的 Django 应用程序中利用 Ajax 表单提交的教程,这样用户就不必重新加载页面。我遇到的问题(我认为)是复选框值作为“打开”发布到我的 Django View ,而它们应该作为“真”发布。

我认为这是错误的原因,因为我在错误日志中看到了这一点:

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'>&times;</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'check。只有当请求是 POST 时才会调用该方法。你要找的是 if request.is_ajax():

希望这对您有所帮助。

关于javascript - 在发布到 Django View 之前将复选框 'on' 转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28823916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com