i have a simple ModelForm:
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
d
As described in Creating forms from models - Selecting the fields to use, there are three ways:
editable=False
. All forms created from the model will exclude the field.fields
attribute in the Meta
inner class to only include the fields you want.exclude
attribute in the Meta
inner class to list the fields you don't want.So if your model has fields field1
, field2
, and field3
and you don't want field3
, technique #2 would look like 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',)
I had the same problem. This is how I made 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 the get_form
method and putting the logic here you can select which Form
you want to have displayed. Above I have displayed the standard form when a condition was met.
One cause I can think of is if your ModelAdmin class which uses your custom form has conflicting settings. For example if you have also explicitly specified 'name' field within 'fields' or 'fieldsets' of your ModelAdmin.
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']
You can use the exclude property to remove fields from a ModelForm
exclude = ('field_name1', 'field_name2,)