django.contrib.auth

该文档提供了 Django 验证系统组件的 API 。有关更多这些组件的用例,或需要自定义验证与鉴权,请参阅 authentication topic guide

User 模型

字段

class models.User

User 对象有如下字段:

username

Required. 150 characters or fewer. Usernames may contain alphanumeric, _, @, +, . and - characters.

The max_length should be sufficient for many use cases. If you need a longer length, please use a custom user model. If you use MySQL with the utf8mb4 encoding (recommended for proper Unicode support), specify at most max_length=191 because MySQL can only create unique indexes with 191 characters in that case by default.

Usernames and Unicode

Django originally accepted only ASCII letters and numbers in usernames. Although it wasn’t a deliberate choice, Unicode characters have always been accepted when using Python 3. Django 1.10 officially added Unicode support in usernames, keeping the ASCII-only behavior on Python 2.

first_name

Optional (blank=True). 30 characters or fewer.

last_name

Optional (blank=True). 150 characters or fewer.

email

Optional (blank=True). Email address.

password

Required. A hash of, and metadata about, the password. (Django doesn’t store the raw password.) Raw passwords can be arbitrarily long and can contain any character. See the password documentation.

groups

Many-to-many relationship to Group

user_permissions

Many-to-many relationship to Permission

is_staff

Boolean. Designates whether this user can access the admin site.

is_active

Boolean. Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts; that way, if your applications have any foreign keys to users, the foreign keys won’t break.

This doesn’t necessarily control whether or not the user can log in. Authentication backends aren’t required to check for the is_active flag but the default backend (ModelBackend) and the RemoteUserBackend do. You can use AllowAllUsersModelBackend or AllowAllUsersRemoteUserBackend if you want to allow inactive users to login. In this case, you’ll also want to customize the AuthenticationForm used by the LoginView as it rejects inactive users. Be aware that the permission-checking methods such as has_perm() and the authentication in the Django admin all return False for inactive users.

is_superuser

布尔值。指定该用户拥有所有权限,而不用一个个开启权限。

last_login

A datetime of the user’s last login.

date_joined

A datetime designating when the account was created. Is set to the current date/time by default when the account is created.

属性

class models.User
is_authenticated

只读属性,始终返回 True (匿名用户 AnonymousUser.is_authenticated 始终返回 False )。这是一种判断用户是否已通过身份验证的方法。这并不意味着任何权限,也不会检查用户是否处于活动状态或是否具有有效会话。即使通常您会根据 request.user 检查这个属性,以确定它是否被 AuthenticationMiddleware 填充(表示当前登录的用户),但是你应该知道该属性对于任何 User 实例都返回True。

is_anonymous

Read-only attribute which is always False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated to this attribute.

方法

class models.User
get_username()

Returns the username for the user. Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.

get_full_name()

Returns the first_name plus the last_name, with a space in between.

get_short_name()

Returns the first_name.

set_password(raw_password)

Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the User object.

When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used.

check_password(raw_password)

如果密码正确则返回’True’。(密码哈希值用于比较)

set_unusable_password()

Marks the user as having no password set. This isn’t the same as having a blank string for a password. check_password() for this user will never return True. Doesn’t save the User object.

如果针对现有外部源(例如LDAP目录)进行应用程序的身份验证,则可能需要这样做。

has_usable_password()

Returns False if set_unusable_password() has been called for this user.

Changed in Django 2.1:

在旧版本中,如果密码是 None 或空字符串或使用不在 PASSWORD_HASHERS 中的哈希,那么也会返回 False 。这个行为被认为是一个 bug ,因为它阻止有这样密码的用户通过请求重置密码。

get_group_permissions(obj=None)

返回用户拥有权限的字符串集合。

如果传入 obj 参数,则只返回指定对象所属组的权限。

get_all_permissions(obj=None)

返回用户拥有权限的字符串集合,同时从用户所属组及用户本身的权限中获取。

如果传入 ``obj``参数,则只返回指定对象和所属组的权限。

has_perm(perm, obj=None)

Returns True if the user has the specified permission, where perm is in the format "<app label>.<permission codename>". (see documentation on permissions). If the user is inactive, this method will always return False. For an active superuser, this method will always return True.

如果传入 obj 参数,则这个方法不会检查该模型权限,而只会检查这个出传入对象的权限。

has_perms(perm_list, obj=None)

Returns True if the user has each of the specified permissions, where each perm is in the format "<app label>.<permission codename>". If the user is inactive, this method will always return False. For an active superuser, this method will always return True.

如果传入参数 obj  ,则这个方法不会检查指定的权限列表,只检查指定对象的权限。

has_module_perms(package_name)

Returns True if the user has any permissions in the given package (the Django app label). If the user is inactive, this method will always return False. For an active superuser, this method will always return True.

email_user(subject, message, from_email=None, **kwargs)

Sends an email to the user. If from_email is None, Django uses the DEFAULT_FROM_EMAIL. Any **kwargs are passed to the underlying send_mail() call.

Manager methods

class models.UserManager

The User model has a custom manager that has the following helper methods (in addition to the methods provided by BaseUserManager):

create_user(username, email=None, password=None, **extra_fields)

Creates, saves and returns a User.

The username and password are set as given. The domain portion of email is automatically converted to lowercase, and the returned User object will have is_active set to True.

If no password is provided, set_unusable_password() will be called.

The extra_fields keyword arguments are passed through to the User’s __init__ method to allow setting arbitrary fields on a custom user model.

See Creating users for example usage.

create_superuser(username, email, password, **extra_fields)

Same as create_user(), but sets is_staff and is_superuser to True.

AnonymousUser object

class models.AnonymousUser

django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences:

In practice, you probably won’t need to use AnonymousUser objects on your own, but they’re used by Web requests, as explained in the next section.

Permission model

class models.Permission

字段

Permission objects have the following fields:

class models.Permission
name

Required. 255 characters or fewer. Example: 'Can vote'.

content_type

Required. A reference to the django_content_type database table, which contains a record for each installed model.

codename

Required. 100 characters or fewer. Example: 'can_vote'.

方法

Permission objects have the standard data-access methods like any other Django model.

Group model

class models.Group

字段

Group objects have the following fields:

class models.Group
name

Required. 150 characters or fewer. Any characters are permitted. Example: 'Awesome Users'.

Changed in Django 2.2:

The max_length increased from 80 to 150 characters.

permissions

Many-to-many field to Permission:

group.permissions.set([permission_list])
group.permissions.add(permission, permission, ...)
group.permissions.remove(permission, permission, ...)
group.permissions.clear()

Validators

class validators.ASCIIUsernameValidator

A field validator allowing only ASCII letters and numbers, in addition to @, ., +, -, and _.

class validators.UnicodeUsernameValidator

A field validator allowing Unicode characters, in addition to @, ., +, -, and _. The default validator for User.username.

Login and logout signals

The auth framework uses the following signals that can be used for notification when a user logs in or out.

user_logged_in()

Sent when a user logs in successfully.

Arguments sent with this signal:

sender
The class of the user that just logged in.
request
The current HttpRequest instance.
user
The user instance that just logged in.
user_logged_out()

Sent when the logout method is called.

sender
As above: the class of the user that just logged out or None if the user was not authenticated.
request
The current HttpRequest instance.
user
The user instance that just logged out or None if the user was not authenticated.
user_login_failed()

Sent when the user failed to login successfully

sender
The name of the module used for authentication.
credentials
A dictionary of keyword arguments containing the user credentials that were passed to authenticate() or your own custom authentication backend. Credentials matching a set of ‘sensitive’ patterns, (including password) will not be sent in the clear as part of the signal.
request
The HttpRequest object, if one was provided to authenticate().

Authentication backends

This section details the authentication backends that come with Django. For information on how to use them and how to write your own authentication backends, see the Other authentication sources section of the User authentication guide.

Available authentication backends

The following backends are available in django.contrib.auth.backends:

class ModelBackend[源代码]

This is the default authentication backend used by Django. It authenticates using credentials consisting of a user identifier and password. For Django’s default user model, the user identifier is the username, for custom user models it is the field specified by USERNAME_FIELD (see Customizing Users and authentication).

It also handles the default permissions model as defined for User and PermissionsMixin.

has_perm(), get_all_permissions(), get_user_permissions(), and get_group_permissions() allow an object to be passed as a parameter for object-specific permissions, but this backend does not implement them other than returning an empty set of permissions if obj is not None.

authenticate(request, username=None, password=None, **kwargs)[源代码]

Tries to authenticate username with password by calling User.check_password. If no username is provided, it tries to fetch a username from kwargs using the key CustomUser.USERNAME_FIELD. Returns an authenticated user or None.

requestHttpRequest ,默认为 None 如果没有被提供给 authenticate() (它把request传给后端).

get_user_permissions(user_obj, obj=None)[源代码]

Returns the set of permission strings the user_obj has from their own user permissions. Returns an empty set if is_anonymous or is_active is False.

get_group_permissions(user_obj, obj=None)[源代码]

Returns the set of permission strings the user_obj has from the permissions of the groups they belong. Returns an empty set if is_anonymous or is_active is False.

get_all_permissions(user_obj, obj=None)[源代码]

Returns the set of permission strings the user_obj has, including both user permissions and group permissions. Returns an empty set if is_anonymous or is_active is False.

has_perm(user_obj, perm, obj=None)[源代码]

Uses get_all_permissions() to check if user_obj has the permission string perm. Returns False if the user is not is_active.

has_module_perms(user_obj, app_label)[源代码]

Returns whether the user_obj has any permissions on the app app_label.

user_can_authenticate()[源代码]

Returns whether the user is allowed to authenticate. To match the behavior of AuthenticationForm which prohibits inactive users from logging in, this method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.

class AllowAllUsersModelBackend[源代码]

Same as ModelBackend except that it doesn’t reject inactive users because user_can_authenticate() always returns True.

When using this backend, you’ll likely want to customize the AuthenticationForm used by the LoginView by overriding the confirm_login_allowed() method as it rejects inactive users.

class RemoteUserBackend[源代码]

Use this backend to take advantage of external-to-Django-handled authentication. It authenticates using usernames passed in request.META['REMOTE_USER']. See the Authenticating against REMOTE_USER documentation.

If you need more control, you can create your own authentication backend that inherits from this class and override these attributes or methods:

create_unknown_user

True or False. Determines whether or not a user object is created if not already in the database Defaults to True.

authenticate(request, remote_user)[源代码]

The username passed as remote_user is considered trusted. This method simply returns the user object with the given username, creating a new user object if create_unknown_user is True.

Returns None if create_unknown_user is False and a User object with the given username is not found in the database.

requestHttpRequest ,默认为 None 如果没有被提供给 authenticate() (它把request传给后端).

clean_username(username)[源代码]

Performs any cleaning on the username (e.g. stripping LDAP DN information) prior to using it to get or create a user object. Returns the cleaned username.

configure_user(request, user)[源代码]

Configures a newly created user. This method is called immediately after a new user is created, and can be used to perform custom setup actions, such as setting the user’s groups based on attributes in an LDAP directory. Returns the user object.

requestHttpRequest ,默认为 None 如果没有被提供给 authenticate() (它把request传给后端).

Changed in Django 2.2:

The request argument was added. Support for method overrides that don’t accept it will be removed in Django 3.1.

user_can_authenticate()

Returns whether the user is allowed to authenticate. This method returns False for users with is_active=False. Custom user models that don’t have an is_active field are allowed.

class AllowAllUsersRemoteUserBackend[源代码]

Same as RemoteUserBackend except that it doesn’t reject inactive users because user_can_authenticate always returns True.

Utility functions

get_user(request)[源代码]

Returns the user model instance associated with the given request’s session.

It checks if the authentication backend stored in the session is present in AUTHENTICATION_BACKENDS. If so, it uses the backend’s get_user() method to retrieve the user model instance and then verifies the session by calling the user model’s get_session_auth_hash() method.

Returns an instance of AnonymousUser if the authentication backend stored in the session is no longer in AUTHENTICATION_BACKENDS, if a user isn’t returned by the backend’s get_user() method, or if the session auth hash doesn’t validate.