bhargava.prabu
bhargava.prabu

Reputation: 708

Allow Only Specific users and superuser to edit a particular field in model

I have a model called test.

Test models have three fields - Question, answer, verified.

Superuser - Admin User1- John User2- Darren

admin.py file

model = Test

    def get_fields(self, request, obj=None):
        fields = ['question','answer','verified']
        if request.user.is_superuser:
            fields.append('verified')
        return fields

This code only allows the superuser to edit the verified record. But what I want is I have to give permission to some of the users to edit this field.

This field should only be visible to admin and john and not to Darren. And Darren will have permission to edit all field in the model except this verified field.

Upvotes: 1

Views: 1207

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can change the line that checks for superuser to add any condition that you like. For instance if you create a group named "admin" this condition will allow users assigned to that group to edit "verified" too

    if request.user.is_superuser or request.user.groups.filter(name='admin').exists():
        fields.append('verified')

Upvotes: 1

Related Questions