Evgenij LegotskojJan. 31, 2020, 2:50 a.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.

# -*- coding: utf-8 -*-

from django.contrib.auth.admin import UserAdmin


class EUserAdmin(UserAdmin):
    def get_readonly_fields(self, request, obj=None):
        # We make the field uneditable if the user is not a superuser
        return super().get_readonly_fields(request) if request.user.is_superuser else ('is_superuser',)

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        # and also exclude all superusers from queryset if the user is not a superuser
        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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Card image cap
Pulsum Via

Project for travelers from EVILEG.

Go
Fornex

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
Share on social networks
Donate

The EVILEG project has switched to a non-commercial basis and will develop solely on the enthusiasm of the site creator, the enthusiasm of users, donations and the hosting referral system

Thank you for your support

Available ways to support the project

PayPal

PatreonYandex.MoneyMore
DP

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
VS

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:0points,
  • Rating points-10
VS

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
Last comments
Ds

Android and QML - Adding Splash Screen

Интересен формат иконки, если это png, то как решается проблема scalability? не растягивается ли лого на китайфонах с 1280х2500? У меня просто сплеш скрин с градиентом и логотипом, и вот несколь…
p

Qt/C++ - Lesson 023. Moving QGraphicsItem on QGraphicsScene with mouse help

FIGURE Abdominopelvic regions. Zjuaqd https://newfasttadalafil.com/ - Cialis Cialis Recommendations for preparing children and adolescents for invasive cardiac procedures a statement…
KG

How to use nested forms in Django

Спасибо за полезную статью. Подскажите пожалуйста, что делать если нужно реализовать большее количество вложенных форм? Например если на модель Address ссылается fk другой модели, на котору…

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

Не думаю, QMediaPlayer в один поток проигрывает. Если вам нужно одновременное воспроизведение нескольких аудиоисточников, то вам нужна Bass audio library , насколько знаю, её обычно и…
AG

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

есть такая вообще возможность ?
Now discuss on the forum
AB

Sorting the added QML elements in the ListModel

I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Изменение поведения QGroupBox при клике на его чекбокс

Я вынес виджеты вынес за пределы QGroupBox в итоге.

QSqlRelatipnalTabelModel Qt 4.8.1 как получить id внешней связи?

Есть еще принципиально другой вариант решить раз и навсегда вопрос с полей id внешней связи. Это форкнуть Qt 4.8.1 QSqlTableModel, то есть создать свою ветку развития. Например создадим кл…

Добавление AndroidManifest.xml в cmake

Добрый день. Как добавить AndroidManifest.xml в cmake? Это не работвет set(ANDROID_PACKAGE_SOURCE_DIR ${PROJECT_SOURCE_DIR}/android CACHE INTERNAL "")set(ANDROID_BUID_DIR ${CMAKE_C…
s

Событие wheelEvent для виджета QLineEdit

вот что получилось: gui.py from PyQt5 import QtCore, QtGui, QtWidgets class LineEdit(QtWidgets.QLineEdit): def wheelEvent(self, event): #print("_") delta = 1 if e…
About
Services
© EVILEG 2015-2022
Recommend hosting TIMEWEB