Field Level Permission Django
Just in case someone else stumble about this, I had some issues with the given accepted answer. Every time the view got refreshed, it appended the fields over and over again. As well to the desired restricted view, where it shouldn't appear.
So, according to the docs, I made it working as follows:
Creating a custom ModelForm
class AbcStaffForm(ModelForm):
class Meta:
model = Abc
exclude = ["manager", "foo", "bar",]
Overwrite get_form() in AbcModelAdmin & refered the custom ModelForm
class AbcAdmin(admin.ModelAdmin):
# some other code
# ...
def get_form(self, request, obj=None, **kwargs):
if not request.user.is_superuser:
kwargs['form'] = AbcStaffForm # ModelForm
return super().get_form(request, obj, **kwargs)
In your admin.py
class ABCAdmin(admin.ModelAdmin):
fields = [.....] # here comes the fields open to all users
def change_view(self, request, object_id, extra_context=None): # override default admin change behaviour
if request.user in gruop2: # an example
self.fields.append('field2') # add field 2 to your `fields`
self.fields.append('field3') # add field 3 to your `fields`
You can use the docs to see what is available. Above is an example taken from one of my usages. You may also need to define change_view
and add_view
too.