【发布时间】:2021-05-19 12:45:06
【问题描述】:
我的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
我在create_superuser 方法中添加字段id 的原因是它是我的模型中的必填字段,我认为在运行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 才能使其正常工作,还是有其他明显的原因导致它不起作用?
【问题讨论】:
-
我不确定为什么会发生错误,但是如果您将 id 字段添加到您的用户模型中,它也会在您创建时包含在超级用户中。因此,您不需要为超级用户定义 id 字段。
-
@SırrıKırımlıoğlu 在我的情况下,id 不是自动设置的,它是一个来自外部的手动 id。对于仅用于测试的超级用户,我不需要它,但我假设超级用户没有保存到数据库中,因为 id 丢失了。这就是为什么我在创建超级用户时尝试包含它的原因。
-
我可以看看你的基本用户模型吗?那我可能会给你一个答案。
标签: python django django-models django-admin