[ACCEPTED]-Remove fields from ModelForm-django

Accepted answer
Score: 14

I had the same problem. This is how I made 5 it work in the new Django (trunk):

class MyModelAdmin(admin.ModelAdmin):
    # Your stuff here..

    def get_form(self, request, obj=None, **kwargs):
        if request.user.is_staff: # condition
            self.exclude = ('field',)
        return super(PublishAdmin, self).get_form(request, obj=obj, **kwargs)

By overriding 4 the get_form method and putting the logic here you 3 can select which Form you want to have displayed. Above 2 I have displayed the standard form when 1 a condition was met.

Score: 7

As described in Creating forms from models - Selecting the fields to use, there are three ways:

  1. In the model, set editable=False. All forms created from the model will exclude the field.
  2. Define the fields attribute in the Meta inner class to only include the fields you want.
  3. Define the exclude attribute in the Meta inner class to list the fields you don't want.

So 3 if your model has fields field1, field2, and field3 and you 2 don't want field3, technique #2 would look like 1 this:

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('field1', 'field2')

And technique #3 would look like this:

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        exclude = ('field3',)
Score: 3

This works great...

def __init__(self, instance, *args, **kwargs):    
    super(FormClass, self).__init__(instance=instance, *args, **kwargs)
    if instance and instance.item:
        del self.fields['field_for_item']


Score: 1

One cause I can think of is if your ModelAdmin 4 class which uses your custom form has conflicting 3 settings. For example if you have also explicitly 2 specified 'name' field within 'fields' or 1 'fieldsets' of your ModelAdmin.

Score: 0

You can use the exclude property to remove 1 fields from a ModelForm

exclude = ('field_name1', 'field_name2,)

More Related questions