How to create user from django shell

前端 未结 7 482
借酒劲吻你
借酒劲吻你 2021-01-30 04:13

When i create user from django-admin user password\'s are encrypted . but when i create user from django shell user-pasword is saved in plain text . Example :

7条回答
  •  滥情空心
    2021-01-30 04:29

    You use user.set_password to set passwords in the django shell. I'm not even sure if directly setting the password via user.password would even work, since Django expects a hash of the password.

    The password field doesn't store passwords; it stores them as $$$, so when it checks a password, it calculates the hash, and compares it. I doubt the user actually has a password whose calculated password hash is in $$$ form.

    If you get the json with all the information needed to create the User, you could just do

    User.objects.create_user(**data)
    

    assuming your passed json is called data.

    Note: This will throw an error if you have extra or missing items in data.

    If you really want to override this behavior, you can do

    def override_setattr(self,name,value):
        if name == 'password':
            self.set_password(value)
        else:
            super().__setattr__(self,name,value) #or however super should be used for your version
    
    User.__setattr__ = override_setattr
    

    I haven't tested this solution, but it should work. Use at your own risk.

提交回复
热议问题