Evgenii Legotckoi
Jan. 31, 2020, 2:50 p.m.

Django - Tutorial 051. How to change queryset and editing ability in ModelAdmin depending on the user

A short note on how to fix the queryset administration form admin.ModelAdmin or UserAdmin . Actually, there is no difference, since the form UserAdmin is inherited from admin.ModelAdmin . Nevertheless, I will show UserAdmin as an example.

The task is as follows. The site has superusers and users from the administration. Superusers can see all users and edit as they like. And administration users can see all user records except superusers, and also can not appoint other users as superusers.


And now to the solution. This form will look as follows.

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.contrib.auth.admin import UserAdmin
  4.  
  5.  
  6. class EUserAdmin(UserAdmin):
  7. def get_readonly_fields(self, request, obj=None):
  8. # We make the field uneditable if the user is not a superuser
  9. return super().get_readonly_fields(request) if request.user.is_superuser else ('is_superuser',)
  10.  
  11. def get_queryset(self, request):
  12. qs = super().get_queryset(request)
  13. # and also exclude all superusers from queryset if the user is not a superuser
  14. return qs if request.user.is_superuser else qs.exclude(is_superuser=True)

Such restrictions are useful if you want to protect the superuser from editing by ordinary users from the administration.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html