'Using Django crispy forms' Layout class with relationship fields

I have a model with lots of related fields (ForeignKey, OneToOneField, ManyToManyField). I want to render it with django crispy forms' FormHelper and Layout classes in forms.py.

But I don't know syntax to get related fields. I've tried like query syntax wit double underscore, but it didn't get populated by instance data:

class Model_A_Form(forms.ModelForm):
    initial_info = forms.CharField(label="Initial info")

    field_1__relfield1 = forms.CharField(label='Field 1.1')
    field_1__relfield2 = forms.CharField(label='Field 1.2')

    field_2__relfield1 = forms.CharField(label='Field 2.1')
    field_2__relfield2 = forms.CharField(label='Field 2.2')


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        tab_1 =     TabHolder(
                            Tab('Tab 1.1',
                                'field_1__name'
                                ),
                            Tab('Tab 1.2',
                                'field_2__name'
                                ),
                        )
        tab_2 =     TabHolder(
                            Tab('Tab 2.1',
                                'field_1__name'
                                ),
                            Tab('Second Tab',
                                'field_2__name'
                                ),
                        )

        layout = Layout(
                    Tab('Tab 1',
                        tab_1
                        ),

                    Tab('Tab 2',
                        tab_2,
                        )
                    )


        self.helper = FormHelper()
        self.helper.layout = layout


    class Meta:
        model = Nizam_Manzum
        fields = (
                    'initial_info',
                    'field_1__relfield1', 
                    'field_1__relfield2',
                    
                    'field_2__relfield1',
                    'field_2__relfield2',
                    )

And I've tried using other forms directly but I got an error about passing Forms as argument to Layout object is can't be done:

        tab_2 =     Tab_2_Form(instance=tab_2_id)

        layout = Layout(
                    Tab('Tab 2',
                        tab_2
                        ),

So is there anyway to get related fields with FormHelper and Layout classes of crispy forms?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source