Adam
Adam

Reputation: 339

Permission to specific field in Django admin panel

I have a model in Django that I want to add instances to it from the admin panel.

I have few users that will have access to the admin panel to create new posts to the model and I have 2 questions:

  1. It is possible to detect witch user is in the panel to auto-detect the field "Author"? (See the red rectangle in the picture)

  2. Can I disable the option to a specific user to mark the "Published" field as true? (See the green rectangle in the picture)

enter image description here

Upvotes: 2

Views: 1334

Answers (1)

Charnel
Charnel

Reputation: 4432

For pre-populating fields you can override get_form method:

def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    form.base_fields['author'].initial = request.user
    return form

For disabling fields you can override...get_readonly_fields as well:

class YourModelAdmin(admin.ModelAdmin):

    readonly_fields = ('whatever', ) # whatever fields you have by default
    limited_fiels = ('published', )

    def get_readonly_fields(self, request, obj=None):
        if request.user.groups.filter(name='YourPermissionGroupName').exists():
            return self.limited_fiels
        return super().get_fieldsets(request, obj=obj)

You may need to override get_fields as well to remove published from changable fields list as well.

Upvotes: 3

Related Questions