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

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


当前回答

如果在/admin/网站需要一个reset_password链接,这是去的方式: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#adding-a-password-reset-feature

其他回答

除了@JamesO的答案,说明使用

python manage.py changepassword [username]

如果你不记得你的用户名:

1-在你的项目的主目录访问数据库(我使用sqlite3):

sqlite3 db.sqlite3

2-列出auth_user表的内容

SELECT * FROM auth_user ;

3-寻找具有is_superuser = 1的用户,在我的例子中是admin 命令输出的截图(我没有足够的代表点)

如果在/admin/网站需要一个reset_password链接,这是去的方式: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#adding-a-password-reset-feature

您可以通过控制台尝试:

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()

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

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

在本例中,我使用的是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()"

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

有两种方法:

changpassword管理命令:

(env) $ python manage.py changepassword <username>

或者(扩展了一些答案,但适用于任何扩展的User模型)使用django-admin shell,如下所示:

(env) $ python manage.py shell

这会弹出shell命令提示符,如下所示:

Python 3.7.2 (default, Mar 27 2019, 08:44:46) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

然后你会想要以下内容:

>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> user = User.objects.get(username='admin@hug.com')
>>> user.set_password('new password')
>>> user.save()
>>> exit()

注:为什么我要用这个答案来回答这个问题?

因为,如前所述,User = get_user_model()将适用于您自己的自定义用户模型。使用from django.contrib.auth.models import User然后User.objects.get(username='username')可能会抛出以下错误:

AttributeError: Manager isn't available; 'auth.User' has been swapped for 'users.User'