我正在使用Django(1.3版),忘记了管理员用户名和密码。如何重置两者?
是否可以将普通用户变为管理员,然后删除管理员状态?
我正在使用Django(1.3版),忘记了管理员用户名和密码。如何重置两者?
是否可以将普通用户变为管理员,然后删除管理员状态?
当前回答
检索用户名和密码的最佳方法之一是查看和更新它们。用户模型提供了一种完美的实现方法。
在本例中,我使用的是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()"
启动服务器,使用用户名和修改后的密码登录。
其他回答
检索用户名和密码的最佳方法之一是查看和更新它们。用户模型提供了一种完美的实现方法。
在本例中,我使用的是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()"
启动服务器,使用用户名和修改后的密码登录。
如果您忘记了您的管理员,那么您需要通过使用创建新用户
python manage.py createsuperuser <username>
对于密码,有CLI命令changepassword用于django修改用户密码
python manage.py changepassword <username>
OR
django-admin changepassword <username>
或者在Django env中运行此代码
from django.contrib.auth.models import User
u = User.objects.get(username='john')
u.set_password('new password')
u.save()
如果在/admin/网站需要一个reset_password链接,这是去的方式: https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#adding-a-password-reset-feature
python manage.py changepassword <user_name>
看文档
以防您不知道这里创建的用户名。您可以获得上述@FallenAngel所描述的用户。
python manage.py shell
from django.contrib.auth.models import User
usrs = User.objects.filter(is_superuser=True)
#identify the user
your_user = usrs.filter(username="yourusername")[0]
#youruser = usrs.get(username="yourusername")
#then set the password
但是,如果您创建了独立的用户模型。一个简单的例子是当您想使用电子邮件作为用户名而不是默认用户名时。在这种情况下,您的用户模型位于your_accounts_app之类的地方。模型那么上面的解决方案将不起作用。 在这种情况下,您可以使用get_user_model方法
from django.contrib.auth import get_user_model
super_users = get_user_model().objects.filter(is_superuser=True)
#proceed to get identify your user
# and set their user password