javascript - (仍然未回答)django 复选框在数据库中保存是或否

标签 javascript django

  <form id="form" name="form">
    <input type="checkbox" value="1" name="Asthma" data-form-field="Option" class="form-check-input display-7" id="checkbox1"  title="Check if Student have Asthma">
    <input type="checkbox" value="1" name="Congenital" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student have Congenital Anomalies">
    <input type="checkbox" value="1" name="Contact" data-form-field="Option" class="form-check-input display-7" id="checkbox1" title="Check if Student use Contact lens">
  </form>

我的 html 中有这段代码
<script type="text/javascript">
                        // when page is ready
                        $(document).ready(function() {
                             // on form submit
                            $("#form").on('submit', function() {
                                // to each unchecked checkbox
                                $(this + 'input[type=checkbox]:not(:checked)').each(function () {
                                    // set value 0 and check it
                                    $(this).attr('checked', true).val(0);
                                });
                            })
                        })
                    </script>

我的问题是每次我将结果保存到我的数据库中时,结果总是自动是,即使我未选中 html 中的复选框(否)。
我不知道我的 javascript 是否正确

这是我的意见.py
    Asthma = request.POST['Asthma']
    Congenital = request.POST['Congenital']
    Contact = request.POST['Contact']
V_insert_data = StudentUserMedicalRecord( 
        Asthma=Asthma,
        CongenitalAnomalies=Congenital,
        ContactLenses=Contact
   )
 V_insert_data.save()

模型.py
Asthma=models.BooleanField(null=True, blank=True, default=False)
CongenitalAnomalies=models.BooleanField(null=True,blank=True, default=False)
ContactLenses=models.BooleanField(null=True,blank=True, default=False)

html.py
enter image description here

即使我从我的 html 插入记录也未选中(否),结果总是在我的数据库中自动"is",你能修复我的 javascript 代码吗?似乎它不起作用。

enter image description here

最佳答案

引用自此来源的文字:https://docs.joomla.org/Talk:Checkbox_form_field_type

同样的问题不仅适用于 Joomla 项目 也适用于使用复选框的其他网络应用程序或网站(特别注意粗体部分)。

Special care needs to be taken with saving an unchecked checkbox from a form!! This is a common mistake for component developers thinking Joomla takes care of this. Joomla doesn't, until now. (Problem in Joomla 2.5 still.)

You see, on saving a form with a checkbox that is unchecked, there is no variable for it in the POST data! So, it's quite common that the value will NOT be overwritten in your DB, especially if it is already on the value that represents "checked" (e.g. 1 ) on the form.



这就是您问题中的 JavaScript 代码段的用途。
// when page is ready
$(document).ready(function() {
  // on form submit
  $("#form").on('submit', function() {
    // to each unchecked checkbox
    $('input[type=checkbox]:not(:checked)').each(function() {
      // set value 0 and check it
      $(this).attr('checked', true).val(0);
    })
  })
})

我删除了 $(this +部分是因为那会破坏事情。

澄清一下:脚本检查未选中的复选框(以确保有一个复选框被发布)。但同时它会更改 checked 中的值状态为 0 (!)

因此,如果您有未选中的框,它们将代表 0,而不是被排除在 POST 请求数据之外。并且当您自己检查项目时,它会不理会它们,它将在复选框的 POST 数据中表示为值 1。

重复的 ID 也是您需要防止的。它不是有效的 HTML5。

你也有这个代码:request.POST['Asthma']
我检查并发现它返回一个 QueryDict .在此页面上发现:
https://docs.djangoproject.com/en/2.2/ref/request-response/#django.http.QueryDict

该页面的示例:
QueryDict('a=1&a=2&c=3')返回:<QueryDict: {'a': ['1', '2'], 'c': ['3']}>
这意味着例如request.POST['Asthma']将始终返回一个列表,该列表可能被强制转换为 bool 类型。所以无论列表中有什么,它都可能转换为 True总是。

所以当你读到它时说:

QueryDict.__getitem__(key)¶ Returns the value for the given key. If the key has more than one value, it returns the last value.



所以更好用__getitem__(key)或其别名:

QueryDict.get(key, default=None)¶ Uses the same logic as getitem(), with a hook for returning a default value if the key doesn’t exist.



当然,使用 JavaScript 片段是您可以使用的一种方法。但是如果你喜欢在你的 Python 代码中处理这个,你可以使用 QueryDict像这样:
Asthma = request.POST.get('Asthma', '0')

关于javascript - (仍然未回答)django 复选框在数据库中保存是或否,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58829631/

相关文章:

javascript - JS 触发器仅在每隔一个页面加载时正确触发

javascript - Angular 映射 http 响应值与另一个 http 调用

javascript - Bootstrap $ ('.multiselect' ).multiselect() CONFLICT

python - django-taggit 删除南表

python - 比较两个 django 的 DateTimeField 信号

javascript - 如何将普通数组转换为 Float32Array?

javascript - 鼠标悬停可显示/隐藏力布局链接

python - Django CMS "No module named html5lib"

django - 如何在 post_save 信号上获取 django 模型中当前登录的用户?

python - 在 Django ModelForm 中添加并初始化自定义字段