'Django admin does not show extra fields added in init method of modelform

I found a couple of questions regarding this, but I specifically wonder about how to add a field in the ModelForms __init__() method.

This is, because I get the number of fields from a function and need to display them in the admin:

class SomeForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ["name", "price",]

    def __init__(self, *args, **kwargs):
        number_of_fields = get_number of fields(kwargs["instance"])
        print(number_of_fields) ## e.g. 3, gives output
        super().__init__(*args, **kwargs)
        for i in range(number_of_fields):
            self.fields[i] = forms.CharField("test", required = False)

But the fields do not show up in the Template Admin edit page. What did I miss? No error popping up either ...



Solution 1:[1]

Try something like this... but you need to pass field name into self.base_fields['name_of_the_field'] somehow

class SomeForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ["name", "price",]
    
    def __init__(self, *args, **kwargs):
        number_of_fields = get_number_of_fields(kwargs["instance"])
        print(number_of_fields) ## e.g. 3, gives output
        
        for i in range(number_of_fields):
            self.base_fields['name_of_the_field'] = forms.CharField(initial="test", required = False)
        
        super(SomeForm, self).__init__(*args, **kwargs)

Sources

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

Source: Stack Overflow

Solution Source
Solution 1