转换复选框' on'发布到Django视图之前的布尔值

时间:2015-03-03 04:06:26

标签: javascript jquery python ajax django

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

所以我按照this教程在我的Django应用程序中利用Ajax表单提交,这样用户就不必重新加载页面了。我遇到的问题(我认为)是复选框值被发送到我的Django视图为'on',而它们应该被POST为'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'>&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"
        )

1 个答案:

答案 0 :(得分:2)

您可以在视图中处理此问题。

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'))

您可以在用户的​​复选框中为您应该收到的所有字段执行此操作。

此外,需要注意的一点是,您不需要在基于类的通用视图的post方法中使用request.method=='POST'检查。只有当请求是POST时才会调用该方法。您要查找的是if request.is_ajax():

希望这有帮助。