A
A
axel2017-10-27 00:21:54
Django
axel, 2017-10-27 00:21:54

How to hide some fields for an individual user in Django?

There is a standard Django admin panel. There are some models registered in it. And there are several users. How can I make it so that one user can see some fields and another can't?
At least take a simple case, without a particularly flexible configuration. Suppose it is known for sure that there are users who have, say, "status A" - he can see all the fields, "status B" - some of the fields, while the fields can be set statically, directly in the code. What are some ideas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2017-10-27
@syschel

See how django generates user creation. There's a function to add users, just displays only certain fields.

class UserAdmin(admin.ModelAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2'),
        }),
    )
    def get_fieldsets(self, request, obj=None):
        if not obj:
            return self.add_fieldsets
        return super(UserAdmin, self).get_fieldsets(request, obj)

If the object has already been created, then prints the default set from the fieldsets tuple.
In general, override get_fieldsets()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question