我正在使用Django(1.3版),忘记了管理员用户名和密码。如何重置两者?

是否可以将普通用户变为管理员,然后删除管理员状态?


当前回答

这是一个很好的问题。

Python manage.py changepassword user_name

例子:-

python manage.py changepassword mickey

其他回答

您可以通过控制台尝试:

python manage.py shell

然后在shell中使用以下脚本

from django.contrib.auth.models import User
User.objects.filter(is_superuser=True)

系统会列出你们所有的超级用户。如果你从列表中认出你的用户名:

usr = User.objects.get(username='your username')
usr.set_password('raw password')
usr.save()

然后你设置一个新密码(:

最好的方法是直接打开你的终端,然后打字

python manage.py createsuperuser

并再次插入另一个密码和用户名 但在大多数情况下,你会丢失一些你之前创建的配置文件。

如果你使用的是自定义用户模型

(venv)your_prj $ ./manage.py shell
>>> from customusers.models import CustomUser
>>> CustomUser.objects.filter(is_superuser=True)
>>> user = CustomUser.objects.get(email="somesuper@sys.com")
>>> user.set_password('@NewPwd')
>>> user.save()
>>> exit()

检索用户名和密码的最佳方法之一是查看和更新它们。用户模型提供了一种完美的实现方法。

在本例中,我使用的是Django 1.9

Navigate to your root directory i,e. where you "manage.py" file is located using your console or other application such as Git. Retrieve the Python shell using the command "python manage.py shell". Import the User Model by typing the following command "from django.contrib.auth.models import User" Get all the users by typing the following command "users = User.objects.all()" Print a list of the users For Python 2 users use the command "print users" For Python 3 users use the command "print(users)" The first user is usually the admin. Select the user you wish to change their password e.g. "user = users[0]" Set the password user.set_password('name_of_the_new_password_for_user_selected') Save the new password "user.save()"

启动服务器,使用用户名和修改后的密码登录。

如果您忘记先创建admin用户,则在manage.py上使用createsuperuser命令创建一个admin用户,然后更改密码。