Note_Tech

All technological notes.


Project maintained by simonangel-fong Hosted on GitHub Pages — Theme by mattgraham

Django - User Object

Back


User objects


Creates users


Creates superusers


Changing passwords


Authenticating users

from django.contrib.auth import authenticate

user = authenticate(username="john", password="secret")
if user is not None:
    # A backend authenticated the credentials
else:
    # No backend authenticated the credentials

User

Fields Description
username Required. < 150 characters
password Required. Raw passwords can be arbitrarily long
first_name Optional. < 150 characters. (blank=True)
last_name Optional. < 150 characters. (blank=True)
email Optional. Email address (blank=True)
groups Many-to-many relationship to Group
user_permissions Many-to-many relationship to Permission
is_staff Whether this user can access the admin site
is_active whether this user account should be considered active.
is_superuser whether this user has all permissions
last_login A datetime of the user’s last login.
date_joined when the account was created.
Attributes Description
is_authenticated Read-only. if the user has been authenticated.
is_anonymous Read-only. if the user has been authenticated.
Methods Description
get_username() the username for the user.
get_full_name() the first_name plus the last_name.
get_short_name() the first_name.
set_password(raw_password) Sets the user’s password
check_password(raw_password) if the given raw string is the correct password for the user.
set_unusable_password() Marks the user as having no password set.
has_usable_password() if set_unusable_password() has been called for this user.
get_user_permissions() a set of permission strings that the user has directly
get_group_permissions() a set of permission strings that the user has, through their groups.
get_all_permissions() a full set of permission strings that the user has
has_perm(perm) if the user has the specified permission
has_perms(perm_list) if the user has each of the specified permissions
has_module_perms(package) if the user has any permissions in the given package
email_user() Sends an email to the user.

models.UserManager

Method Description
create_user(username) Creates, saves and returns a User.
create_superuser(username) Creates, saves and returns a Superuser.
with_perm(perm) Returns users that have the given permission perm.

Example

# py manage.py shell
user = User.objects.create_user('john',"lennon@thebeatles.com", 'johnpassword')
user                                    # <User: john>
user.username                           # 'john'
user.email                              # lennon@thebeatles.com'
user.is_authenticated                   # True
user.is_anonymous                       # False
user.get_username()                     # 'john'
user.check_password('johnpassword')     # True
user.get_all_permissions()              # set()

AnonymousUser


TOP