[ACCEPTED]-Remove fields from ModelForm-django
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.
As described in Creating forms from models - Selecting the fields to use, there are three ways:
- In the model, set
editable=False
. All forms created from the model will exclude the field. - Define the
fields
attribute in theMeta
inner class to only include the fields you want. - Define the
exclude
attribute in theMeta
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',)
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']
0
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.
You can use the exclude property to remove 1 fields from a ModelForm
exclude = ('field_name1', 'field_name2,)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.