First of all, you should know that we do not use model forms, because this is the only way to do something. The goal is time gain. Therefore, it is impossible to do all this staff. Personally, when I encounter these kinds of situations, I always create the form manually, but fill out only the first or highest model of the hierarchy, and for the rest I will use Ajax.For For example:
def myController(request):
And then in your template:
<select name="myChoice" id="choice"> {% for pays in your_dic_variable %} <option value={{ pays.id }}>{{ pays.nom }}</option> {% endfor %} </select> ....
And if you have another option, you can call the onChange() method to send an Ajax request to dynamically update the next list. As you said, if you know that you are using Ajax, you will have something like this:
$(function(){ $('#choice')change(function() {
Or, another idea is that, imagine there are 3 models:
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)
As in ThirdModel , fields that depend on the two previous models, second_model , you can use model forms to have only 3 fields: fields_m3 , field2 and field3 . They will be generated by auto:
class ThirdModelForm(froms.ModelForm): class Meta: model=ThirdModel fields=['fields_m3','field2','field3']
And in your template you will do this:
<form> {{ csrf_token }} <select id="choice"> {% for f_model in your_dic_variable %} <option value={{ f.id }}>{{ f.column }}</option> {% endfor %} </select> <select id="choice2"> {% for f_model in your_dic_variable %} <option value={{ f.id }}>{{ f.column }}</option> {% endfor %} </select> <select id="choice2"> </select> <select id="choice2"> </select> {{ ourform.as_p }} <button type='submit'>Record</button> </form>
I did this too and it works great