Skip to content Skip to sidebar Skip to footer

Conditional Fields In A Modelform.meta

Assume we have a custom user model in a Django application. In order to make it CRUDable from the admin page, we want to define some forms. Below is the UserChangeForm used to modi

Solution 1:

You can delete fields from the form in the __init__() constructor:

classUserChangeForm(forms.ModelForm):

    classMeta:
        fields = ('email', 'company_name', 'headquarters',
                           'first_name', 'last_name', )

    def__init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        if self.instance.is_company:
            fields_to_delete = ('first_name', 'last_name')
        else:
            fields_to_delete = ('company_name', 'headquarters')
        for field in fields_to_delete:
            del self.fields[field]

Solution 2:

If you're using the Django admin, you can use the ModelAdmin.get_fields method.

classUserModelAdmin(admin.ModelAdmin):
    ...
    defget_fields(request, obj=None):
        if obj isNone:
            return ('email', ...) # suitable list of fields for adding objectelif obj.is_company:
            return ('email', 'company_name', 'headquarters')
        else:
            return ('email', 'first_name', 'last_name')

Post a Comment for "Conditional Fields In A Modelform.meta"