using User.objects.get_or_create() gives invalid password format in django?

我的梦境 提交于 2020-01-13 03:00:13

问题


python manage.py shell

>>> from django.contrib.auth.models import User
>>> u=User.objects.get_or_create(username="testuser2",password="123")
>>> u
(<User: testuser2>, True)

seems it created the User properly. but when I logged into admin at http://127.0.0.1:8000/admin/auth/user/3/, I see this message for password Invalid password format or unknown hashing algorithm.

Screenshot is attached too. why is it this way and how to create User objects from shell. I am actually writing a populating script that create mulitple users for my project?


回答1:


You need to use the User.set_password method to set a raw password.

E.g.,

from django.contrib.auth.models import User
user, created = User.objects.get_or_create(username="testuser2")
user.set_password('123')
user.save()



回答2:


Almost correct except we don't want to set password of existing users

from django.contrib.auth.models import User
user, created = User.objects.get_or_create(username="testuser2")
if created:
          # user was created
          # set the password here
          user.set_password('123')
          user.save()
       else:
          # user was retrieved



回答3:


As mentioned in the documentation.

The most direct way to create users is to use the included create_user() helper function.

from django.contrib.auth.models import User user = User.objects.create_user(username="testuser2",password="123")



来源:https://stackoverflow.com/questions/22924122/using-user-objects-get-or-create-gives-invalid-password-format-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!