django.contrib.auth
¶
このドキュメントでは、Django の 認証システムのコンポーネントの API リファレンス資料を提供しています。 これらのコンポーネントの使い方や、認証と承認をカスタマイズする方法の詳細は、 認証トピックガイド を参照してください。
User
モデル¶
-
class
models.
User
¶
フィールド¶
-
class
models.
User
User
オブジェクトには、以下のフィールドがあります:-
username
¶ 必須です。150 文字以下です。英数字のほか、
_
、@
、+
、.
、-
が使えます。max_length
は多くの状況で十分のはずです。もしより長い文字数が必要な場合は、独自のユーザモデル を参照してください。utf8mb4
エンコーディングで MySQL を使っている場合は (適切な Unicode をサポートするために推奨されています)、最大でもmax_length=191
としてください。なぜなら、MySQL は、でおフォルトでは 191 文字まででしかユニークインデックスを作成できないからです。
-
first_name
¶ Optional (
blank=True
). 150 characters or fewer.
-
last_name
¶ Optional (
blank=True
). 150 characters or fewer.
-
email
¶ Optional (
blank=True
). Email address.
-
password
¶ 必須です。パスワードのハッシュであり、パスワードについてのメタデータでもあります。(Django は生のパスワードを保管しません。) 生のパスワードは、任意の長さで、あらゆる文字を使用可能です。詳しくは password documentation を参照してください。
-
user_permissions
¶ Permission
への多対多のリレーションシップです。
-
is_staff
¶ 真偽値です。ユーザが admin サイトにアクセスできるかどうかを指定します。
-
is_active
¶ 真偽値です。 このユーザアカウントをアクティブと見なすかどうかを指定します。 アカウントを削除するのではなく、このフラグを
False
に設定することをお勧めします。 そうすれば、アプリケーションに外部キーがある場合でも、外部キーが破損しません。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 theRemoteUserBackend
do. You can useAllowAllUsersModelBackend
orAllowAllUsersRemoteUserBackend
if you want to allow inactive users to login. In this case, you'll also want to customize theAuthenticationForm
used by theLoginView
as it rejects inactive users. Be aware that the permission-checking methods such ashas_perm()
and the authentication in the Django admin all returnFalse
for inactive users.
-
is_superuser
¶ 真偽値です。明示的にアサインすることなく全てのパーミッションを持たせるかどうかを指定します。
-
last_login
¶ ユーザーが最後にログインした日時です。
-
date_joined
¶ いつアカウントが作成されたかを示す日時です。アカウントが作成されたとき、デフォルトでは現在の日時がセットされます。
-
属性¶
-
class
models.
User
-
is_authenticated
¶ (
AnonymousUser.is_authenticated
が常にFalse
なのとは対照的に) 常にTrue
の読み取り専用属性です。ユーザが認証済みかどうかを知らせる方法です。これはパーミッションという意味ではなく、ユーザーがアクティブかどうか、また有効なセッションがあるかどうかをチェックするわけでもありません。 通常、request.user
のこの属性をチェックしてAuthenticationMiddleware
(現在ログイン中のユーザを表します) によって格納されているかどうかを調べます。User
のインスタンスの場合、この属性はTrue
となります。
-
is_anonymous
¶ 常に
False
の読み取り専用属性です。User
オブジェクトとAnonymousUser
オブジェクトを区別する方法です。一般的に、is_authenticated
を使う方が好ましいと言えます。
-
メソッド¶
-
class
models.
User
-
get_username
()¶ ユーザのユーザ名を返します。
User
モデルはスワップアウトされることがあるので、ユーザ名を直接参照する代わりにこのメソッドを使う必要があります。
-
get_full_name
()¶ first_name
とlast_name
をスペースでつないだ文字列を返します。
-
get_short_name
()¶ first_name
を返します。
-
set_password
(raw_password)¶ 指定された生の文字列に、ユーザのパスワードをセットし、パスワードのハッシュ処理を行います。
User
は保存しません。raw_password
がNone
のとき、set_unusable_password()
が使われるのと同じように、パスワードは使用に適さないパスワードになります。
-
check_password
(raw_password)¶ 与えられた生の文字列が、ユーザに対して正しいパスワードであれば
True
を返します。 (比較する際にはパスワードハッシュを処理します。)
-
set_unusable_password
()¶ ユーザにパスワードが設定されていないものとしてマークします。これは、パスワードに空の文字列を付けることと同じではありません。ユーザに対する
check_password()
はTrue
を返しません。User
オブジェクトを保存しません。アプリケーションの認証が LDAP ディレクトリなどの既存の外部ソースに対して行われている場合は、これが必要になることがあります。
-
has_usable_password
()¶ ユーザに対して
set_unusable_password()
が呼ばれている場合、False
を返します。
-
get_user_permissions
(obj=None)¶ Returns a set of permission strings that the user has directly.
If
obj
is passed in, only returns the user permissions for this specific object.
-
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 returnFalse
. For an active superuser, this method will always returnTrue
.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 returnFalse
. For an active superuser, this method will always returnTrue
.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 returnFalse
. For an active superuser, this method will always returnTrue
.
-
email_user
(subject, message, from_email=None, **kwargs)¶ ユーザに E メール送信します。
from_email
がNone
の場合、Django はDEFAULT_FROM_EMAIL
を使用します。全ての**kwargs
は元となるsend_mail()
呼び出しに渡されます。
-
マネージャメソッド¶
-
class
models.
UserManager
¶ User
モデルは、(BaseUserManager
で提供されるメソッドに加えて) 以下のヘルパーメソッドを有する独自のマネージャを持っています:-
create_user
(username, email=None, password=None, **extra_fields)¶ User
を作成、保存して返します。The
username
andpassword
are set as given. The domain portion ofemail
is automatically converted to lowercase, and the returnedUser
object will haveis_active
set toTrue
.If no password is provided,
set_unusable_password()
will be called.The
extra_fields
keyword arguments are passed through to theUser
’s__init__
method to allow setting arbitrary fields on a custom user model.See Creating users for example usage.
-
create_superuser
(username, email=None, password=None, **extra_fields)¶ create_user()
と同じですが、is_staff
とis_superuser
をTrue
にセットします。
-
with_perm
(perm, is_active=True, include_superusers=True, backend=None, obj=None)¶ Returns users that have the given permission
perm
either in the"<app label>.<permission codename>"
format or as aPermission
instance. Returns an empty queryset if no users who have theperm
found.If
is_active
isTrue
(default), returns only active users, or ifFalse
, returns only inactive users. UseNone
to return all users irrespective of active state.If
include_superusers
isTrue
(default), the result will include superusers.If
backend
is passed in and it's defined inAUTHENTICATION_BACKENDS
, then this method will use it. Otherwise, it will use thebackend
inAUTHENTICATION_BACKENDS
, if there is only one, or raise an exception.
-
AnonymousUser
オブジェクト¶
-
class
models.
AnonymousUser
¶ django.contrib.auth.models.AnonymousUser
は、django.contrib.auth.models.User
インターフェースを実装するクラスで、以下の点が異なります。- id が常に
None
です。 username
が常に空の文字列です。get_username()
が常に空の文字列を返します。is_anonymous
がFalse
ではなくTrue
です。is_authenticated
がFalse
ではなくTrue
です。is_staff
とis_superuser
が常にFalse
です。is_active
が常にFalse
です。groups
とuser_permissions
が常に空です。set_password()
、check_password()
、save()
、delete()
がNotImplementedError
を投げます。
- id が常に
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
モデル¶
-
class
models.
Permission
¶
フィールド¶
Permission
オブジェクトには以下のフィールドがあります:
メソッド¶
他のあらゆる Django モデル と同じように、 Permission
オブジェクトも標準的なデータアクセスのメソッドが使えます。
Group
モデル¶
-
class
models.
Group
¶
フィールド¶
Group
オブジェクトには以下のフィールドがあります:
-
class
models.
Group
-
name
¶ Required. 150 characters or fewer. Any characters are permitted. Example:
'Awesome Users'
.
-
permissions
¶ Permission
への多対多のフィールドです:group.permissions.set([permission_list]) group.permissions.add(permission, permission, ...) group.permissions.remove(permission, permission, ...) group.permissions.clear()
-
バリデータ¶
-
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 forUser.username
.
ログインとログアウトのシグナル¶
認証フレームワークは、ユーザーがログインやログアウトをしたときの通知に使うことができる、以下の signals を使用します。
-
user_logged_in
¶ ユーザがログインに成功したときに送信されます。
このシグナルとともに送信される引数は以下の通りです:
sender
- たった今ログインしたユーザのクラスです。
request
- 現在の
HttpRequest
インスタンスです。 user
- たった今ログインしたユーザのインスタンスです。
-
user_logged_out
¶ logout メソッドが呼ばれたときに送信されます。
sender
- 上記の通り: たった今ログアウトしたユーザのクラス、もしくはユーザが認証されなかった場合は
None
となります。 request
- 現在の
HttpRequest
インスタンスです。 user
- たった今ログアウトしたユーザのインスタンスか、ユーザが認証されなかった場合は
None
です。
-
user_login_failed
¶ ユーザがログインに失敗したときに送信されます。
sender
- 認証のために使われるモジュールの名前です。
credentials
authenticate()
か独自の認証バックエンドに渡されたユーザ資格情報を含む、キーワード引数のディクショナリです。'sensitive' パターンのセットに一致する (パスワードを含んだ) 資格情報は、シグナルの一部として明確には送信されません。request
- The
HttpRequest
object, if one was provided toauthenticate()
.
認証のバックエンド¶
このセクションでは、Django に付属する認証バックエンドについて詳しく説明します。 使用方法と独自の認証バックエンドの作成方法については、ユーザ認証ガイド の 他の認証ソースのセクション を参照してください。
利用可能な認証バックエンド¶
以下のバックエンドが django.contrib.auth.backends
内で利用可能です:
-
class
BaseBackend
¶ A base class that provides default implementations for all required methods. By default, it will reject any user and provide no permissions.
-
get_user_permissions
(user_obj, obj=None)¶ Returns an empty set.
-
get_group_permissions
(user_obj, obj=None)¶ Returns an empty set.
-
get_all_permissions
(user_obj, obj=None)¶ Uses
get_user_permissions()
andget_group_permissions()
to get the set of permission strings theuser_obj
has.
-
has_perm
(user_obj, perm, obj=None)¶ Uses
get_all_permissions()
to check ifuser_obj
has the permission stringperm
.
-
-
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
andPermissionsMixin
.has_perm()
,get_all_permissions()
,get_user_permissions()
, andget_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 ifobj is not None
.with_perm()
also allows an object to be passed as a parameter, but unlike others methods it returns an empty queryset ifobj is not None
.-
authenticate
(request, username=None, password=None, **kwargs)¶ Tries to authenticate
username
withpassword
by callingUser.check_password
. If nousername
is provided, it tries to fetch a username fromkwargs
using the keyCustomUser.USERNAME_FIELD
. Returns an authenticated user orNone
.request
はHttpRequest
で、authenticate()
が提供されていない場合None
となる可能性があります。(バックエンドでこれを通過するため).
-
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 ifis_anonymous
oris_active
isFalse
.
-
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 ifis_anonymous
oris_active
isFalse
.
-
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 ifis_anonymous
oris_active
isFalse
.
-
has_perm
(user_obj, perm, obj=None)¶ Uses
get_all_permissions()
to check ifuser_obj
has the permission stringperm
. ReturnsFalse
if the user is notis_active
.
-
has_module_perms
(user_obj, app_label)¶ Returns whether the
user_obj
has any permissions on the appapp_label
.
-
user_can_authenticate
()¶ Returns whether the user is allowed to authenticate. To match the behavior of
AuthenticationForm
whichprohibits inactive users from logging in
, this method returnsFalse
for users withis_active=False
. Custom user models that don't have anis_active
field are allowed.
-
with_perm
(perm, is_active=True, include_superusers=True, obj=None)¶ Returns all active users who have the permission
perm
either in the form of"<app label>.<permission codename>"
or aPermission
instance. Returns an empty queryset if no users who have theperm
found.If
is_active
isTrue
(default), returns only active users, or ifFalse
, returns only inactive users. UseNone
to return all users irrespective of active state.If
include_superusers
isTrue
(default), the result will include superusers.
-
-
class
AllowAllUsersModelBackend
¶ Same as
ModelBackend
except that it doesn't reject inactive users becauseuser_can_authenticate()
always returnsTrue
.When using this backend, you'll likely want to customize the
AuthenticationForm
used by theLoginView
by overriding theconfirm_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
orFalse
. Determines whether or not a user object is created if not already in the database Defaults toTrue
.
-
authenticate
(request, remote_user)¶ The username passed as
remote_user
is considered trusted. This method returns the user object with the given username, creating a new user object ifcreate_unknown_user
isTrue
.Returns
None
ifcreate_unknown_user
isFalse
and aUser
object with the given username is not found in the database.request
はHttpRequest
で、authenticate()
が提供されていない場合None
となる可能性があります。(バックエンドでこれを通過するため).
-
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, created=True)¶ Configures the user on each authentication attempt. This method is called immediately after fetching or creating the user being authenticated, 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.
The setup can be performed either once when the user is created (
created
isTrue
) or on existing users (created
isFalse
) as a way of synchronizing attributes between the remote and the local systems.request
はHttpRequest
で、authenticate()
が提供されていない場合None
となる可能性があります。(バックエンドでこれを通過するため).Changed in Django 4.1:The
created
argument was added.
-
user_can_authenticate
()¶ Returns whether the user is allowed to authenticate. This method returns
False
for users withis_active=False
. Custom user models that don't have anis_active
field are allowed.
-
-
class
AllowAllUsersRemoteUserBackend
¶ Same as
RemoteUserBackend
except that it doesn't reject inactive users becauseuser_can_authenticate
always returnsTrue
.
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'sget_user()
method to retrieve the user model instance and then verifies the session by calling the user model'sget_session_auth_hash()
method. If the verification fails andSECRET_KEY_FALLBACKS
are provided, it verifies the session against each fallback key usingget_session_auth_fallback_hash()
.Returns an instance of
AnonymousUser
if the authentication backend stored in the session is no longer inAUTHENTICATION_BACKENDS
, if a user isn't returned by the backend'sget_user()
method, or if the session auth hash doesn't validate.Changed in Django 4.1.8:Fallback verification with
SECRET_KEY_FALLBACKS
was added.