Django在CustomUserAdmin中设置权限时得到Keyerror

bgibtngc  于 2023-01-31  发布在  Go
关注(0)|答案(1)|浏览(174)

你好,我是Python/Django初学者,在实现权限方面遇到了问题。我也从教程中复制了这个,但它似乎在我的应用中不起作用。
我想要达到什么目标:这是关于管理模块。在那里我希望只有管理员可以改变字段的相同名称。应该只有一个用户或员工用户登录,这个字段应该是灰色的。与以下代码,这也工作得很好。但是,如果我然后一个新用户,然后创建/添加我得到一个Keyerror,这也是指内置代码。
附上属于该主题的代码问题片段:

    • 管理员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)

Tutorial中的代码是在大约52分钟时解释的以下代码。
我的www.example.com在我实现这段代码之前运行良好: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

当我开始这程序一切工作在first.only当我想要到添加一个新用户作为一个登录的用户我得到这下面的错误信息

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']

回溯的最后几行是:

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'

我用了两种形式:

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",
        )

谁能帮帮我,谢谢

h79rfbju

h79rfbju1#

这是解决方案,我必须在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

相关问题