【问题标题】:HTML select form with option to enter value does not store the entered value as object field in django带有输入值选项的 HTML 选择表单不会将输入的值存储为 django 中的对象字段
【发布时间】:2019-10-01 19:26:02
【问题描述】:

我有一个 Django 表单,其中有几个下拉菜单,可以选择输入自定义值。 为了输入自定义值,每当从此实现http://jsfiddle.net/6nq7w/4/ 选择自定义值时,我都会使用以下实现来切换文本框@

每当我从下拉列表中选择一个选项并保存表单时,模型的对象值(在本例中为 EmployeeInformation.dept)都会保留所选值,但如果我输入自定义值则不是这种情况。

在下面的示例中,我使用链式下拉实现根据部门 ID 加载部门。

例如 - 假设在填写表单时我选择值 Sales 然后选择 EmployeeInformation.dept = Sales 的值,而当我选择选项为 Enter Manually 并输入新值时说 @987654325 @django模型对象不把这个手动输入的值作为字段Dept的数据。

models.py

class EmployeeInformation(models.Model):
    name = models.Charfield(max_length=30,null=False, blank=False)
    dept_id = models.ForeignKey(DepartmentInformation, on_delete=models.SET_NULL, null=True)
    dept = models.ForeignKey(SubDeptInformation, on_delete=models.SET_NULL, null=True)
    salary = models.DecimalField(null=True, blank=True, decimal_places=2, max_digits=10)

form.html

<!DOCTYPE html>
<html>
<script>
function toggleField(hideObj,showObj){
  hideObj.disabled=true;        
  hideObj.style.display='none';
  showObj.disabled=false;   
  showObj.style.display='inline';
  showObj.focus();
}
</script>
<body>
<form name="EmployeeInformation" action="#">
Department: <select name="browser" 
          onchange="if(this.options[this.selectedIndex].value=='Enter Manually'){
              toggleField(this,this.nextSibling);
              this.selectedIndex='0';
          }">
            <option></option>
            <option value="Enter Manually">[Enter Manually]</option>
            <option>HR</option>
            <option>Sales</option>
            <option>Finance</option>
        </select><input name="Dept" style="display:none;" disabled="disabled" 
            onblur="if(this.value==''){toggleField(this,this.previousSibling);}">
<input type="submit" value="Submit">
</form>
</body>
</html>

views.py

class AddEmployeeInfo(CreateView):
    model = EmployeeInformation
    form_class = EmployeeForm
    template_name = 'form.html'
    success_url = reverse_lazy('employee_list')

如何将手动输入的值存储为模型对象字段的值,即在我的示例中为EmployeeInformation.dept.name

提前感谢您的任何帮助!

【问题讨论】:

    标签: javascript html django django-models django-forms


    【解决方案1】:

    DeptXYZ 或任何手动输入的部门在数据库中不存在。

    deptEmployeeInformation 模型具有 ForeignKey 关系。因此,要存储DeptXYZ 或任何其他手动输入的部门,该部门应该存在于数据库中。由于DeptXYZ 不存在于数据库中,Django 将存储null

    要存储DeptXYZ 或任何其他手动输入的部门,您需要先创建相应的部门。您将需要覆盖AddEmployeeInfoform_valid() 方法,如here 所述,首先创建并保存手动输入的部门。

    希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 2021-12-28
      • 2017-02-18
      • 2023-03-15
      • 2019-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多