Home > Back-end >  Django get Keyerror while set permissions in CustomUserAdmin
Django get Keyerror while set permissions in CustomUserAdmin

Time:01-27

Hi I am a Python/Django beginner and have a problem with the implementation of a permission thing. I have also copied this from a tutorial, but it doesn't seem to work within my app.

What do I want to achieve: It's about the admin module. There I want that only administrators can change the field with the same name. Should only a user or staff user have logged in, this field should be grayed out. with the following code, this also works wonderfully. However, if I then a new user then create / add I get a Keyerror, which also refers to the built-in code.

Attached my code question segments that belong to the topic:

admin.py

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import JobTitle, JobSkill, SkillSet


CustomUser = get_user_model()

@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
   # see tutorial to this stuff: https://www.youtube.com/watch?v=wlYaUvfXJDc
def get_form(self, request, obj=None, **kwargs):
    form = super().get_form(request, obj, **kwargs)
    is_superuser = request.user.is_superuser

    if not is_superuser:
        form.base_fields["is_superuser"].disabled = True
        form.base_fields["user_permissions"].disabled = True
        form.base_fields["groups"].disabled = True
    return form

add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = CustomUser
readonly_fields = ["last_login", "date_joined"]
list_display = [
    "username",
    "employed",
    "email",
    "job_title",
    "is_active",
    "is_staff",
    "is_superuser",
]

fieldsets = (
    (
        None,
        {
            "fields": (
                "username",
                "password",
                "first_name",
                "last_name",
            )
        },
    ),
    (
        "Persönliche Information",
        {
            "fields": ("birth_date", "employed", "job_title", "skill_set"),
        },
    ),
    (
        "Adresse und Kontakt",
        {
            "classes": ("collapse",),
            "fields": (
                "email",
                "mobile_number",
                "phone_number",
                "street_name",
                "street_number",
                "zip_code",
                "city",
                "country",
            ),
        },
    ),
    (
        "Berechtigungen",
        {
            "classes": ("collapse",),
            "fields": (
                "is_active",
                "is_staff",
                "is_superuser",
                "groups",
                "user_permissions",
            ),
        },
    ),
    (
        "Anmelde Daten",
        {
            "classes": ("collapse",),
            "fields": (
                "last_login",
                "date_joined",
            ),
        },
    ),
)


class JobTitleAdmin(admin.ModelAdmin):
    readonly_fields = ("created_at", "updated_at")


admin.site.register(JobTitle, JobTitleAdmin)
admin.site.register(JobSkill)
admin.site.register(SkillSet)

in the Tutorial is the following code explained at about 52 Minutes.

my admin.py runs fine before i implemented this code:

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        is_superuser = request.user.is_superuser

    if not is_superuser:
        form.base_fields["is_superuser"].disabled = True
        form.base_fields["user_permissions"].disabled = True
        form.base_fields["groups"].disabled = True
    return form

when i start the program everything works at first. only when i want to add a new user as a logged in user i get the following error message

KeyError at /admin/people/customuser/add/

'is_superuser'

Request Method:     GET
Request URL:    http://localhost:8000/admin/people/customuser/add/
Django Version:     4.1.5
Exception Type:     KeyError
Exception Value:    

'is_superuser'

Exception Location:     /cpp_base/people/admin.py, line 25, in get_form
Raised during:  django.contrib.auth.admin.add_view
Python Executable:  /usr/local/bin/python
Python Version:     3.10.4
Python Path:    

['/cpp_base',
 '/usr/local/lib/python310.zip',
 '/usr/local/lib/python3.10',
 '/usr/local/lib/python3.10/lib-dynload',
 '/usr/local/lib/python3.10/site-packages']

the last lines of the traceback are:

File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in
_wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line
1750, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 
1786, in _changeform_view
ModelForm = self.get_form(
File "/cpp_base/people/admin.py", line 25, in get_form
form.base_fields["is_superuser"].disabled = True
KeyError: 'is_superuser'

here are the two forms, i used:

from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm,
UserChangeForm


class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = get_user_model()
        fields = (
            "username",
            "email",
            "birth_date",
            "mobile_number",
            "phone_number",
            "job_title",
            "skill_set",
        )


class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = get_user_model()
        fields = (
            "username",
            "email",
            "birth_date",
            "mobile_number",
            "phone_number",
            "job_title",
            "skill_set",
        )

who can help me please, thank you

CodePudding user response:

here is the solution, i have to add this check for loop in my CustomUserAdmin

@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin):
    # see tutorial to this stuff: https://www.youtube.com/watch?v=wlYaUvfXJDc
    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        is_superuser = request.user.is_superuser

        if not is_superuser:
            disabled_fields = {"is_superuser", "user_permissions", "groups", "is_staff"}
            for f in disabled_fields:
                if f in form.base_fields:
                    form.base_fields[f].disabled = True
        return form
  • Related