Problem in creating dynamic form fields in Django App using crispy form

I have one Model Given as below:-

class FeeItemAmount(models.Model):
    id = models.AutoField(primary_key=True)
    fee_item = models.ForeignKey(FeeItem, on_delete=models.CASCADE)
    class_obj = models.ForeignKey(Classes, on_delete=models.CASCADE)
    amount = models.IntegerField()

For creating new item I wanted to populate the Classes objects from model and based on that we will show the Form fields. One amount field for each class. In code I am doing that by:-

name = forms.CharField(label="Name", max_length=100)
months_list = forms.MultipleChoiceField(label='Months', widget=forms.CheckboxSelectMultiple,choices=months_name_list)
due_date = forms.IntegerField(label="Due Date",required=False)

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    classes = Classes.objects.all()
    for class_obj in classes:
        field_name = 'class_%s' % (class_obj.id,)
        self.fields[field_name] = forms.IntegerField(label=class_obj.name,required=False)
    self.helper = FormHelper()
    self.helper.form_class = 'form-horizontal'
    self.helper.form_tag = False
    self.helper.label_class = 'col-sm-3'
    self.helper.field_class = 'col-sm-9'
    self.helper.layout = Layout(
        Div(
            Div('name', css_class='form-group col-sm-6 mb-0 border border-secondary'),
            Div('due_date', css_class='form-group col-sm-6 mb-0 border border-secondary'),
            css_class='form-row'),
        Div(
            Div(InlineCheckboxes('months_list'), css_class='form-group col-sm-12 mb-0 border border-secondary'),
            css_class='form-row'),
        Div(
            HTML("<p> Provide Amount for following Classes for this Fee Item:</p>"),
            css_class='form-row'),
    )

Now the problem is that those dynamically created fields are not showing in the Form. If I remove the Layout part of the code than those fields are showing but than it is not in the format that i want. I am new to Django and crispy form. I searched on google for this. One solution i found to use Slicing of the Layout by using :-

form.helper.all().wrap()
form.helper.wrap_together()

But I am not knowing where to add this.

Please help me out of this. Is there any good documentation for creating Dynamic Form field.

Back to Top