我有一个 ModelForm,其中包含 boolean 字段和 CheckboxInput。 MYSQL 数据库中 boolean 字段默认提供 0 (False) 和 1 (True) 值。
该表单是模态的,使用 JSON 输出模型中的内容。当 JSON 文件添加内容时,它会输入 True 或 False。
当我尝试将复选框输入的值从 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 函数来更改该值,然后可以将值更改为“开”,但在将其关闭时则不起作用。然后我收到以下消息。
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. AForm
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/