Skip to content Skip to sidebar Skip to footer

Field Level Permission Django

Today i came up with a requirement where i need to implement field level permission so looking for the best possible way. class ABC(models.Model): field1 = ..... fiel

Solution 1:

In your admin.py

classABCAdmin(admin.ModelAdmin):
    fields = [.....]  # here comes the fields open to all usersdefchange_view(self, request, object_id, extra_context=None):  # override default admin change behaviourif 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.

Solution 2:

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

classAbcStaffForm(ModelForm):
    class Meta:
        model = Abc
        exclude = ["manager", "foo", "bar",]

Overwrite get_form() in AbcModelAdmin & refered the custom ModelForm

classAbcAdmin(admin.ModelAdmin):
    # some other code# ...defget_form(self, request, obj=None, **kwargs):
        ifnot request.user.is_superuser:
            kwargs['form'] = AbcStaffForm  # ModelFormreturnsuper().get_form(request, obj, **kwargs)

Solution 3:

You can also override readonly_fields in changeform_view.

Try this in admin.py

classABCAdmin(admin.ModelAdmin):defchangeform_view(self, request, *args, **kwargs)self.readonly_fields = list(self.readonly_fields)
        if request.user ingroup:#or another conditionself.readonly_fields.append('field2')

        returnsuper(ABCAdmin, self).changeform_view(request, *args, **kwargs)

Post a Comment for "Field Level Permission Django"