详解Django的 create_superuser() 函数:创建超级用户

  • Post category:Python

Django 中自带的 create_superuser() 函数是用于创建超级用户的,通常在开发过程中使用。该函数可以为新用户创建一个带有管理员权限的超级用户账号,这个账号可以拥有所有权限,并且在应用中不能被删除。

使用 create_superuser() 函数需要先获取 Django 的认证模块(from django.contrib.auth.models import User)并导入 User 类。你需要调用 create_superuser() 函数并在其中填入三个必填的参数:用户名、邮箱和密码。

如果不想在终端输入密码使用 Python 自动加密密码,则需要额外导入 Django 的密码模块(from django.contrib.auth.hashers import make_password)并调用 make_password() 函数。make_password() 函数将接受一个字符串参数作为用户密码并返回加密后的密码哈希字符串。

以下是一个示例,演示如何使用 create_superuser() 创建一个超级用户:

from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password

# 创建一个超级用户
User.objects.create_superuser(
    username = 'admin', 
    email = 'admin@example.com', 
    password = make_password('password'))

除此之外,以下是另一个示例,展示 create_superuser() 函数的另一种用法:

from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password

# 为用户提供 superuser 属性并创建超级用户
user = User.objects.create(
    username='admin',
    email='admin@example.com',
    password=make_password('password'),
    is_superuser=True,
)

在这个示例中,我们创建了一个新的用户并将 is_superuser 属性设置为 True。该用户将自动成为超级用户(即创建一个管理员账号)。

总之,create_superuser() 函数是用于创建 Django 超级用户的方便工具。在 Django 的应用程序开发中,该函数是一个非常有用的工具。通过使用该函数,您可以轻松创建带有管理员权限的超级用户。