Django - 复选框输入的布尔字段

Django - Boolean Fields on Checkbox Input

我有一个 ModelForm,它有 Boolean Field 和 CheckboxInput。在 MYSQL 数据库中,布尔字段默认提供值 0(假)和 1(真)。

表单是模态的,使用 JSON 从模型输出内容。当 JSON 文件添加内容时,它会输入 True 或 False。

当我尝试将 Checkbox Input 的值从 False 更改并提交到 True 时出现问题。当我尝试这样做时,我收到以下消息:

奇怪的是,这反过来起作用,允许我提交从 True 到 False 的更改。

下面是代码(我只包含了问题所在的字段。)该字段是 First_Time_Booking

型号。

first_time_booking = models.BooleanField()

表单小部件。

'first_time_booking': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'bfbw_edit_first_time_booking', 'name': 'bfbw_edit_first_time_booking'}),

查看

def update_bfbw(request):
    if request.method == 'POST':
        bfbw_booking_id = request.POST.get('bfbw_booking_ref')
        bfbw_data = BFBWBookings.objects.get(id=bfbw_booking_id)
        bfbw_data.school_name = request.POST['school_name']
        bfbw_data.first_time_booking = request.POST.get('first_time_booking', False)
        bfbw_data.save()
    else:
        print(form.errors)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

我已经尝试编写一个 If 函数来更改值,然后可以将值更改为 On 但在关闭时不会。然后我收到以下消息。

if request.POST['first_time_booking'] == 'on':
            bfbw_data.first_time_booking = True
        else:
            bfbw_data.first_time_booking = False

这方面的任何帮助都会很棒。预先感谢您的任何回复。

该值为 "on"(如果用户已选中该复选框),或者 存在(如果用户未选中该复选框)。

因此您可以使用:

bfbw_data.first_time_booking = request.POST<b>.get(</b>'first_time_booking'<b>)</b> == 'on'

Note: It is better to use a Form [Django-doc] than to perform manual validation and cleaning of the data. A Form will not only simplify rendering a form in HTML, but it also makes it more convenient to validate the input, and clean the data to a more convenient type.