我一直在研究这个问题几天,没有运气。希望有人在那里可以提供帮助。
假设我们有以下模型:
User model (django.contrib.auth.models)
class Children(models.Model):
name = models.CharField(max_length=200, blank=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
目标:当新用户要创建帐户时,他们将填写“用户”表单,并能够向其帐户中添加x个孩子。本质上,模板将具有一个用户表单,并且x个子表单(取决于用户拥有多少个子表单)全部捆绑在同一
可以有多种解决方案,显然有一些解决方法和使用JavaScript。我可以提到一个我相信它会满足您的需求。
<!--This is the form for parents and Javascript inserts Dynamic Fields -->
<form id="parent_form" method="POST" action="{% url 'url_name' %}">
<input type="text" name="parent_name">
<input id="child_count" onchange="inject_child_details()"
type="number" name="number_of_children" min=0>
<div id="child_details">
enter code here
</div>
</form>
<script type="text/javascript" nonce="{{script_nonce}}">
function inject_child_details() {
var x = document.getElementById("child_count").value;
details_div = document.getElementById("child_details");
details_div.innerHTML = ''
for(var index = 1;index <= x;){
details_div.insertAdjacentHTML('beforeend','<input type="text" name="child'+index+'name" placeholder="Name of Child '+index+'">');
index = index +1;
}
}
</script>
要插入的HTML应该在一行中,或者应使用]截断>
'+
下一行应以上述倒排开头+'