首页 > 解决方案 > 在 Django 中创建超级用户时如何定义额外的字段?

问题描述

我有这个models.py

class UserManager(BaseUserManager):

    def create_user(self, name, password=None):

        """

        Creates and saves a User with the given name and password.

        """

        if not name:

            raise ValueError('A user must have a name.')



        user = self.model()

        user.set_password(password)

        user.save(using=self._db)

        return user



    def create_staffuser(self, name, password):

        """

        Creates and saves a staff user with the given name and password.

        """

        user = self.create_user(

            name,

            password=password,

        )

        user.staff = True

        user.save(using=self._db)

        return user



    def create_superuser(self, name, password, id):

        """

        Creates and saves a superuser with the given name and password.

        """

        user = self.create_user(

            name,

            id,

            password=password,

        )

        user.staff = True

        user.admin = True

        user.save(using=self._db)

        return user

id我在我的-method 中添加该字段的原因create_superuser是它是我的模型中的必填字段,我认为我需要在运行时也包含它python manage.py createsuperuser。我的问题是我不知道如何自定义超级用户的创建。有了这个我总是得到错误TypeError: create_superuser() missing 1 required positional argument: 'id'。我还尝试从函数中删除 id。然后该过程没有错误,但我无法登录管理站点,它说用户名或密码不正确。我有这个admin.py

from django.contrib import admin

from django.contrib.auth import get_user_model

from django.contrib.auth.models import Group

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

from .forms import UserAdminCreationForm, UserAdminChangeForm


User = get_user_model()


# Remove Group Model from admin. We're not using it.

admin.site.unregister(Group)


class UserAdmin(BaseUserAdmin):

    # The forms to add and change user instances

    form = UserAdminChangeForm

    add_form = UserAdminCreationForm



    # The fields to be used in displaying the User model.

    # These override the definitions on the base UserAdmin

    # that reference specific fields on auth.User.

    list_display = ['name', 'admin']

    list_filter = ['admin']

    fieldsets = (

        (None, {'fields': ('name', 'password')}),

        ('Personal info', {'fields': ()}),

        ('Permissions', {'fields': ('admin',)}),

    )

    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin

    # overrides get_fieldsets to use this attribute when creating a user.

    add_fieldsets = (

        (None, {

            'classes': ('wide',),

            'fields': ('name', 'password1', 'password2')}

        ),

    )

    search_fields = ['name']

    ordering = ['name']

    filter_horizontal = ()


admin.site.register(User, UserAdmin)

我是否需要修改admin.py-file 才能使其正常工作,还是有其他明显的原因导致它不起作用?

标签: pythondjangodjango-modelsdjango-admin

解决方案


在任何情况下,手动赋予 id 值都是非常糟糕的做法。id 应该是自动生成的。但是如果你真的想获取 id 作为函数参数,那么你需要重写 Django 命令来创建一个超级用户。

您可以在此处阅读自定义 Django 管理命令的详细信息。 https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/


推荐阅读