django 我如何添加自定义字段到管理面板的用户模型

ssm49v7z  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(127)

如何将用户模型的自定义字段添加到管理页面?
我定义了一个Char字段来抽象User。虽然我可以在数据库中看到这个字段,但在Django管理面板中看不到。我创建了一个Meta类并写入了我的字段,但它在管理面板上仍然不可见。
这个问题不会发生在我的自定义模型上,只会发生在Django的用户模型上。谁能告诉我为什么会这样,我该怎么做?

vlurs2pr

vlurs2pr1#

做这样的事,可能会起作用。

from django.contrib.auth.admin import UserAdmin as BaseUserAdmin

@admin.register(User)
class UserAdmin(BaseUserAdmin):
    fieldsets = (
        (None, {"fields": ("username", "password")}),
        (
            "Personal info",
            {
                "fields": (
                    "first_name",
                    "last_name",
                    "email",
                    "phone",
                    "personnel_code",
                    "role",
                    "national_code",
                    "branch",
                    "manager",
                )
            },
        ),
        (
            "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"),
            },
        ),
        (
            "Personal info",
            {
                "fields": (
                    "first_name",
                    "last_name",
                    "email",
                    "phone",
                    "personnel_code",
                    "role",
                    "national_code",
                    "branch",
                    "manager",
                )
            },
        ),
        (
            "Permissions",
            {
                "fields": (
                    "is_active",
                    "is_staff",
                    "is_superuser",
                    # "groups",
                    "user_permissions",
                )
            },
        ),
    )

字符串
你可以把你的领域任何你想要的。
我希望这对你有用。

相关问题