Django - 复选框输入上的 boolean 字段

标签 django django-models django-forms boolean

我有一个 ModelForm,其中包含 boolean 字段和 CheckboxInput。 MYSQL 数据库中 boolean 字段默认提供 0 (False) 和 1 (True) 值。

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

当我尝试将复选框输入的值从 False 更改并提交为 True 时,会出现此问题。当我尝试此操作时,我收到以下消息:

enter image description here

奇怪的是,这正好相反,允许我提交从 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 函数来更改该值,然后可以将值更改为“开”,但在将其关闭时则不起作用。然后我收到以下消息。

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

enter image description here

对此的任何帮助都会很棒。预先感谢您的回复。

最佳答案

该值为“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.

关于Django - 复选框输入上的 boolean 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67667942/

相关文章:

python - 当你有 book.publisher 和 book.author 时如何获得 publisher.authors?

html - 将一个 HTML 文件导入另一个 HTML 文件

python - 模型字段的外键?

django - 使用 Django 创建可编辑的 HTML 表格

带有大表的 Django M2M

django - 在不使用表单的模型上设置字段

django - 为什么 Django 使用 is_staff 和 is_superuser 而不是将它们作为权限?

python - Django——模型不存在,但 Django 仍然加载它们

django - 管理员将模型数据导出到 csv/excel 文件

django - 从 Django Auth 中的 UserChangeForm 中排除用户名或密码