在发布到Django vi之前,将复选框“on”转换为布尔值

2024-04-27 19:59:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以我按照this教程在Django应用程序中利用Ajax表单提交,这样用户就不必重新加载页面了。我遇到的问题(我想)是复选框值被作为'on'发布到我的Django视图,而它们应该被发布为'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视图.py在这里:https://gist.github.com/joefusaro/25b6221536291c1ba0d1

更新: 我已经添加了相关的Django模板和表单代码here。并不是说我使用widget_tweaks来呈现表单。表单呈现如下:

^{pr2}$

最终更新

感谢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
        }
    });
};

这是决赛视图.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"
        )

Tags: thedjangonameformlogidjsondata
1条回答
网友
1楼 · 发布于 2024-04-27 19:59:36

你可以在视图中处理这个。在

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'检查。只有当请求为波斯特。什么您要找的是if request.is_ajax():

希望这有帮助。在

相关问题 更多 >