How to create user from django shell

shifu picture shifu · Aug 29, 2013 · Viewed 93.5k times · Source

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 :

{
    "date_joined": "2013-08-28T04:22:56.322185",
    "email": "",
    "first_name": "",
    "id": 5,
    "is_active": true,
    "is_staff": false,
    "is_superuser": false,
    "last_login": "2013-08-28T04:22:56.322134",
    "last_name": "",
    "password": "pbkdf2_sha256$10000$iGKbck9CED0b$6hWrKYiMPNGKhcfPVGal2YP4LkuP3Qwem+2ydswWACk=",
    "resource_uri": "/api/v1/user/5/",
    "username": "user4"
},
{
    "date_joined": "2013-08-29T01:15:36.414887",
    "email": "test@ophio",
    "first_name": "",
    "id": 6,
    "is_active": true,
    "is_staff": true,
    "is_superuser": true,
    "last_login": "2013-08-29T01:15:36.414807",
    "last_name": "",
    "password": "123test",
    "resource_uri": "/api/v1/user/6/",
    "username": "test3"
} 

I am trying to make REST style api for a simple blog app : when i try to insert a user by post request [ by passing JSON ] password is saved as plain text. how to override this behaviour.

Answer

Daniel Roseman picture Daniel Roseman · Aug 29, 2013

You should not create the user via the normal User(...) syntax, as others have suggested. You should always use User.objects.create_user(), which takes care of setting the password properly.

user@host> manage.py shell
>>> from django.contrib.auth.models import User
>>> user=User.objects.create_user('foo', password='bar')
>>> user.is_superuser=True
>>> user.is_staff=True
>>> user.save()