首先,你必须知道,我们不使用模型表格,因为它是唯一的做事方式。目的是获得时间。所以手动完成所有这些人员并非不可能。个人,当我面对这些时在某些情况下,我总是手动构建表单,但只填充层次结构的第一个或最高模型,对于其他模型,我将使用 Ajax。例如:
def myController(request):
#To have the list of all you pays
pays=Pays.objects.all()
#Here you pass your pays object in your form template by a dictionnary
return render(request,"template/your_form_template.html",{"your_dic_variable":pays})
然后在你的模板中:
<select name="myChoice" id="choice">
{% for pays in your_dic_variable %}
<option value={{ pays.id }}>{{ pays.nom }}</option>
{% endfor %}
</select>
....
如果您有其他选择,您可以调用 onChange() 方法发送 Ajax 请求以动态更新以下下拉列表。正如您所说,如果您知道使用 Ajax,您将拥有一些东西像这样:
$(function(){
$('#choice')change(function()
{
//you can send ajax somewhere here
});
});
或者,另一个想法是,想象有 3 个这样的模型:
class FirstModel(models.model):
field_m1=models.CharField(max_length=20)
class SecondModel(models.model):
field_m2=models.CharField(max_length=20)
first_model=models.ForeignKey(FirstModel,on_delete=models.CASCADE)
class ThirdModel(models.model):
field_m3=models.CharField(max_length=20)
field2=models.CharField(max_length=20)
field3=models.CharField(max_length=20)
second_model=models.ForeignKey(SecondModel,on_delete=models.CASCADE)
如ThirdModel中依赖于前两个模型的字段是second_model,您可以使用模型表单只有3个字段:fields_m3、field2和field3。它们将被生成自动:
class ThirdModelForm(froms.ModelForm):
class Meta:
model=ThirdModel
fields=['fields_m3','field2','field3']
在你的模板中你会这样做:
<form>
{{ csrf_token }}
<!-- Data form first model,but you must have a controller send send the data -->
<select id="choice">
{% for f_model in your_dic_variable %}
<option value={{ f.id }}>{{ f.column }}</option>
{% endfor %}
</select>
<!-- second model will be populated with ajax form the choice1 id -->
<select id="choice2">
{% for f_model in your_dic_variable %}
<option value={{ f.id }}>{{ f.column }}</option>
{% endfor %}
</select>
<!-- second dropdown will be populated with ajax form the choice1 id -->
<select id="choice2">
<!-- data here will come from ajax according to the first model id value -->
</select>
<!-- third dropdown will be populated with ajax form the choice2 id,and it is the second_model field of ThirdModel data -->
<select id="choice2">
<!-- data here will come from ajax according to the second model id value -->
</select>
{{ ourform.as_p }}
<button type='submit'>Record</button>
</form>
我也做了,效果很好