Django 1.8.2 中文文档

django.contrib.auth

这份文档提供Django 认证系统组件的API 参考资料。对于这些组件的用法以及如何自定义认证和授权请参照认证主题的相关指南

User

字段

class models.User

User 对象具有如下字段:

username

必选。少于等于30个字符。 用户名可以包含字母、数字、_@+.- 字符。

first_name

可选。 少于等于30个字符。

last_name

可选。少于30个字符。

email

可选。邮箱地址。

password

必选。 密码的哈希及元数据。(Django 不保存原始密码)。原始密码可以无限长而且可以包含任意字符。参见密码相关的文档

groups

Group 之间的多对多关系。

user_permissions

Permission 之间的多对多关系。

is_staff

布尔值。指示用户是否可以访问Admin 站点。

is_active

布尔值。指示用户的账号是否激活。我们建议把这个标记设置为False 来代替删除账号;这样的话,如果你的应用和User 之间有外键关联,外键就不会失效。

它不是用来控制用户是否能够登录。认证的后端没有要求检查is_active 标记,而且默认的后端不会检查。如果你想在is_activeFalse 时拒绝用户登录,你需要在你自己的视图或自定义的认证后端中作检查。但是,默认的login() 视图使用的AuthenticationForm 作这个检查,正如在Django 的Admin 站点中所做的权限检查方法如has_perm() 和认证一样。对于未激活的用户,所有这些函数/方法都返回False

is_superuser

布尔值。指定这个用户拥有所有的权限而不需要给他们分配明确的权限。

last_login

用户最后一次登录的时间。

Changed in Django 1.8:

如果这个用户没有登录过,这个字段将会是null以前默认设置成当前的date/time。

date_joined

账户创建的时间。当账号创建时,默认设置为当前的date/time。

方法

class models.User
get_username()

返回这个User 的username。因为User 模型可以置换,你应该使用这个方法而不要直接访问username 属性。

is_anonymous()

永远返回False这是区别UserAnonymousUser 对象的一种方法。一般情况下,相比这个方法更建议你使用is_authenticated()

is_authenticated()

永远返回True(与AnonymousUser.is_authenticated() 永远返回False 相反)。这是区分用户是否已经认证的一种方法。它不检查权限、用户是否激活以及是否具有一个合法的会话。即使通常你将在request.user上面 调用这个方法来确认用户是否已经被AuthenticationMiddleware 填充(表示当前登录的用户),你应该明白这个方法对于任何User 实例都返回True

get_full_name()

返回first_namelast_name,之间带有一个空格。

get_short_name()

返回first_name

set_password(raw_password)

设置用户的密码为给定的原始字符串,并负责密码的哈希。不会保存User 对象。

raw_passwordNone 时,密码将设置为一个不可用的密码,和使用set_unusable_password() 的效果一样。

check_password(raw_password)

Returns True if the given raw string is the correct password for the user.(它负责在比较时密码的哈希)。

set_unusable_password()

标记用户为没有设置密码。它与密码为空的字符串不一样。check_password() 对这种用户永远不会返回True不会保存User 对象。

如果你的认证发生在外部例如LDAP 目录时,可能需要这个函数。

has_usable_password()

如果对这个用户调用过set_unusable_password(),则返回False

get_group_permissions(obj=None)

返回一个用户当前拥有的权限的set,通过用户组

如果传入obj,则仅返回此特定对象的组权限。http://python.usyiyi.cn/translate/django_182/ref/contrib/auth.html#

get_all_permissions(obj=None)

Returns a set of permission strings that the user has, both through group and user permissions.

If obj is passed in, only returns the permissions for this specific object.

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.

If obj is passed in, this method won’t check for a permission for the model, but for this specific object.

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.

If obj is passed in, this method won’t check for permissions for the model, but for the specific object.

has_module_perms(package_name)

如果用户具有给出的package(Django 的应用标签)中的权限,则返回True如果用户没有激活,这个方法将永远返回 False

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

发生邮件给这个用户。如果from_emailNone,Django 将使用DEFAULT_FROM_EMAIL

Changed in Django 1.7:

任何**kwargs 都将传递给底层的send_mail() 调用。

管理器方法

class models.UserManager

User 模型有一个自定义的管理器,它具有以下辅助方法(除了BaseUserManager 提供的方法之外):

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

创建、保存并返回一个User

usernamepassword 设置为给出的值。email 的域名部分将自动转换成小写,返回的User 对象将设置is_activeTrue

如果没有提供password,将调用 set_unusable_password()

extra_fields 关键字参数将传递给User__init__ 方法,以允许设置自定义User 模型 的字段。

参见创建用户 中的示例用法。

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

create_user() 相同,但是设置is_staffis_superuserTrue

匿名用户

class models.AnonymousUser

django.contrib.auth.models.AnonymousUser 类实现了django.contrib.auth.models.User 接口,但具有下面几个不同点:

New in Django 1.8:

新增AnonymousUser.get_username() 以更好地模拟 django.contrib.auth.models.User

在实际应用中,你自己可能不需要使用AnonymousUser 对象,它们用于Web 请求,在下节会讲述。

权限

class models.Permission

字段

Permission 对象有以下字段:

class models.Permission
name

必填项. 255个字符或者更少. 例如: 'Can vote'.

Changed in Django 1.8:

max_length 属性从50个字符增加至255个字符

content_type

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

codename

必须项.小于等于100个字符.例如: 'can_vote'.

方法

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

用户群组 Group

class models.Group

字段

Group 对象有以下字段:

class models.Group
name

必填项,80个字符以内。允许任何字符. 例如: 'Awesome Users'.

permissions

Many-to-many field to Permission:

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

登陆和注销标识

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.

认证使用的后台

这一节详细讲述Django 自带的认证后台。关于如何使用它们以及如何编写你自己的认证后台,参见用户认证指南 中的其它认证源一节

可用的认证后台

以下是django.contrib.auth.backends 中可以使用的后台:

class ModelBackend[source]

这是Django使用的默认认证后台。它使用由用户标识和密码组成的凭据进行认证。对于Django的默认用户模型,用户的标识是用户名,对于自定义的用户模型,它通过USERNAME_FIELD 字段表示(参见自定义Users 和认证)。

它还处理 UserPermissionsMixin 定义的权限模型。

has_perm(), get_all_permissions(), get_user_permissions(), 和get_group_permissions() 允许一个对象作为特定权限参数来传递, 如果条件是 if obj is not None. 后端除了返回一个空的permissions 外,并不会去完成他们。

authenticate(username=None, password=None, **kwargs)[source]

通过调用User.check_password 验证usernamepassword如果username 没有提供,它会使用CustomUser.USERNAME_FIELD 关键字从kwargs 中获取username。返回一个认证过的User 或None

get_user_permissions(user_obj, obj=None)[source]
New in Django 1.8.

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)[source]

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)[source]

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)[source]

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(self, user_obj, app_label)[source]

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

class RemoteUserBackend[source]

使用这个后台来处理Django的外部认证。. 它使用 request.里面的usernames来进行验证。META['REMOTE_USER']. See the Authenticating against REMOTE_USER documentation.

如果你需要更多的控制,你可以创建你自己的验证后端,继承这个类,并重写这些属性或方法:

RemoteUserBackend.create_unknown_user

True or False. 决定是否有一个 User 对象已经在数据库中创建。Defaults to True.

RemoteUserBackend.authenticate(remote_user)[source]

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.

RemoteUserBackend.clean_username(username)[source]

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.

RemoteUserBackend.configure_user(user)[source]

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.