[Django]-Dynamically including/excluding fields from Meta class of a Django ModelForm

3👍

You can modify form fields via __init__:

from django import forms

class Foo(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if condition:
            self.fields.pop('field1')

    class Meta:
        model = SomeModel
        fields = ('field1', 'field2', 'field3')

Note that this can cause the form’s validation to fail if the field is required.

A better approach might be to hide the field, instead of removing it entirely:

class Foo(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if condition:
            form.fields['field1'].widget = forms.HiddenInput()

    class Meta:
        model = SomeModel
        fields = ('field1', 'field2', 'field3')

Leave a comment