【发布时间】: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