django.contrib.authLink to this heading
このドキュメントでは、Django の 認証システムのコンポーネントの API リファレンス資料を提供しています。 これらのコンポーネントの使い方や、認証と承認をカスタマイズする方法の詳細は、 認証トピックガイド を参照してください。
User モデルLink to this heading
フィールドLink to this heading
- class models.UserLink to this definition
Userオブジェクトには、以下のフィールドがあります:- usernameLink to this definition
必須です。150 文字以下です。英数字のほか、
_、@、+、.、-が使えます。max_lengthは多くの状況で十分のはずです。もしより長い文字数が必要な場合は、独自のユーザモデル を参照してください。utf8mb4エンコーディングで MySQL を使っている場合は (適切な Unicode をサポートするために推奨されています)、最大でもmax_length=191としてください。なぜなら、MySQL は、でおフォルトでは 191 文字まででしかユニークインデックスを作成できないからです。
- first_nameLink to this definition
Optional (
blank=True). 30 characters or fewer.
- last_nameLink to this definition
Optional (
blank=True). 150 characters or fewer.
- emailLink to this definition
Optional (
blank=True). Email address.
- passwordLink to this definition
必須です。パスワードのハッシュであり、パスワードについてのメタデータでもあります。(Django は生のパスワードを保管しません。) 生のパスワードは、任意の長さで、あらゆる文字を使用可能です。詳しくは password documentation を参照してください。
- groupsLink to this definition
Groupへの多対多のリレーションシップです。
- user_permissionsLink to this definition
Permissionへの多対多のリレーションシップです。
- is_staffLink to this definition
真偽値です。ユーザが admin サイトにアクセスできるかどうかを指定します。
- is_activeLink to this definition
真偽値です。 このユーザアカウントをアクティブと見なすかどうかを指定します。 アカウントを削除するのではなく、このフラグを
Falseに設定することをお勧めします。 そうすれば、アプリケーションに外部キーがある場合でも、外部キーが破損しません。This doesn't necessarily control whether or not the user can log in. Authentication backends aren't required to check for the
is_activeflag but the default backend (ModelBackend) and theRemoteUserBackenddo. You can useAllowAllUsersModelBackendorAllowAllUsersRemoteUserBackendif you want to allow inactive users to login. In this case, you'll also want to customize theAuthenticationFormused by theLoginViewas it rejects inactive users. Be aware that the permission-checking methods such ashas_perm()and the authentication in the Django admin all returnFalsefor inactive users.
- is_superuserLink to this definition
真偽値です。明示的にアサインすることなく全てのパーミッションを持たせるかどうかを指定します。
- last_loginLink to this definition
ユーザーが最後にログインした日時です。
- date_joinedLink to this definition
いつアカウントが作成されたかを示す日時です。アカウントが作成されたとき、デフォルトでは現在の日時がセットされます。
属性Link to this heading
- class models.UserLink to this definition
- is_authenticatedLink to this definition
(
AnonymousUser.is_authenticatedが常にFalseなのとは対照的に) 常にTrueの読み取り専用属性です。ユーザが認証済みかどうかを知らせる方法です。これはパーミッションという意味ではなく、ユーザーがアクティブかどうか、また有効なセッションがあるかどうかをチェックするわけでもありません。 通常、request.userのこの属性をチェックしてAuthenticationMiddleware(現在ログイン中のユーザを表します) によって格納されているかどうかを調べます。Userのインスタンスの場合、この属性はTrueとなります。
- is_anonymousLink to this definition
常に
Falseの読み取り専用属性です。UserオブジェクトとAnonymousUserオブジェクトを区別する方法です。一般的に、is_authenticatedを使う方が好ましいと言えます。
メソッドLink to this heading
- class models.UserLink to this definition
- get_username()Link to this definition
ユーザのユーザ名を返します。
Userモデルはスワップアウトされることがあるので、ユーザ名を直接参照する代わりにこのメソッドを使う必要があります。
- get_full_name()Link to this definition
first_nameとlast_nameをスペースでつないだ文字列を返します。
- get_short_name()Link to this definition
first_nameを返します。
- set_password(raw_password)Link to this definition
指定された生の文字列に、ユーザのパスワードをセットし、パスワードのハッシュ処理を行います。
Userは保存しません。raw_passwordがNoneのとき、set_unusable_password()が使われるのと同じように、パスワードは使用に適さないパスワードになります。
- check_password(raw_password)Link to this definition
与えられた生の文字列が、ユーザに対して正しいパスワードであれば
Trueを返します。 (比較する際にはパスワードハッシュを処理します。)
- set_unusable_password()Link to this definition
ユーザにパスワードが設定されていないものとしてマークします。これは、パスワードに空の文字列を付けることと同じではありません。ユーザに対する
check_password()はTrueを返しません。Userオブジェクトを保存しません。アプリケーションの認証が LDAP ディレクトリなどの既存の外部ソースに対して行われている場合は、これが必要になることがあります。
- has_usable_password()Link to this definition
ユーザに対して
set_unusable_password()が呼ばれている場合、Falseを返します。
- get_group_permissions(obj=None)Link to this definition
ユーザがグループを通して持つパーミッションの文字列のセットを返します。
objが渡されたとき、指定されたオブジェクトに対するグループパーミッションのみを返します。
- get_all_permissions(obj=None)Link to this definition
ユーザがグループおよびユーザパーミッションを通して持つパーミッションの文字列のセットを返します。
objが渡された場合、指定されたオブジェクトに対するパーミッションのみを返します。
- has_perm(perm, obj=None)Link to this definition
ユーザが指定されたパーミッションを持っている場合、
Trueを返します。perm は"<app label>.<permission codename>"形式です。(permissions のドキュメントを参照)。ユーザが非アクティブの場合、このメソッドは常にFalseを返します。objが渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。
- has_perms(perm_list, obj=None)Link to this definition
ユーザが指定されたそれぞれのパーミッションを持っている場合、
Trueを返します。各パーミッションは"<app label>.<permission codename>"形式です。ユーザが非アクティブの場合、このメソッドは常にFalseを返します。objが渡された場合、このメソッドは指定されたオブジェクトに対してパーミッションのチェックを行い、モデルに対しては行いません。
- has_module_perms(package_name)Link to this definition
ユーザが指定されたパッケージ (Django のアプリケーションラベル)内の全パーミッションを持っている場合、
Trueを返します。ユーザが非アクティブの場合、このメソッドは常にFalseを返します。
- email_user(subject, message, from_email=None, **kwargs)Link to this definition
ユーザに E メール送信します。
from_emailがNoneの場合、Django はDEFAULT_FROM_EMAILを使用します。全ての**kwargsは元となるsend_mail()呼び出しに渡されます。
マネージャメソッドLink to this heading
- class models.UserManagerLink to this definition
Userモデルは、(BaseUserManagerで提供されるメソッドに加えて) 以下のヘルパーメソッドを有する独自のマネージャを持っています:- create_user(username, email=None, password=None, **extra_fields)Link to this definition
Userを作成、保存して返します。The
usernameandpasswordare set as given. The domain portion ofemailis automatically converted to lowercase, and the returnedUserobject will haveis_activeset toTrue.If no password is provided,
set_unusable_password()will be called.The
extra_fieldskeyword 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, password, **extra_fields)Link to this definition
create_user()と同じですが、is_staffとis_superuserをTrueにセットします。
AnonymousUser オブジェクトLink to this heading
- class models.AnonymousUserLink to this definition
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を投げます。
実際には、AnonymousUser オブジェクトを自分自身で使う必要はないかもしれませんが、次のセクションで説明するように、Web リクエストで使用されます。
Permission モデルLink to this heading
- class models.PermissionLink to this definition
フィールドLink to this heading
Permission オブジェクトには以下のフィールドがあります:
- class models.PermissionLink to this definition
- nameLink to this definition
必須です。255 文字以下です。例:
'Can vote'。
- content_typeLink to this definition
必須です。
django_content_typeデータベーステーブルへの参照で、インストールされた各モデルのレコードを含みます。
- codenameLink to this definition
必須です。100 文字以下です。例:
'can_vote'。
メソッドLink to this heading
他のあらゆる Django モデル と同じように、Permission オブジェクトも標準的なデータアクセスのメソッドが使えます。
Group モデルLink to this heading
- class models.GroupLink to this definition
フィールドLink to this heading
Group オブジェクトには以下のフィールドがあります:
- class models.GroupLink to this definition
- nameLink to this definition
必須です。80以下です。あらゆる文字列が使えます。例:
'Awesome Users'。
- permissionsLink to this definition
Permissionへの多対多のフィールドです:group.permissions.set([permission_list]) group.permissions.add(permission, permission, ...) group.permissions.remove(permission, permission, ...) group.permissions.clear()
バリデータLink to this heading
- class validators.ASCIIUsernameValidatorLink to this definition
A field validator allowing only ASCII letters and numbers, in addition to
@,.,+,-, and_.
- class validators.UnicodeUsernameValidatorLink to this definition
A field validator allowing Unicode characters, in addition to
@,.,+,-, and_. The default validator forUser.username.
ログインとログアウトのシグナルLink to this heading
認証フレームワークは、ユーザーがログインやログアウトをしたときの通知に使うことができる、以下の signals を使用します。
- user_logged_in()Link to this definition
ユーザがログインに成功したときに送信されます。
このシグナルとともに送信される引数は以下の通りです:
senderたった今ログインしたユーザのクラスです。
request現在の
HttpRequestインスタンスです。userたった今ログインしたユーザのインスタンスです。
- user_logged_out()Link to this definition
logout メソッドが呼ばれたときに送信されます。
sender上記の通り: たった今ログアウトしたユーザのクラス、もしくはユーザが認証されなかった場合は
Noneとなります。request現在の
HttpRequestインスタンスです。userたった今ログアウトしたユーザのインスタンスか、ユーザが認証されなかった場合は ``None``です。
- user_login_failed()Link to this definition
ユーザがログインに失敗したときに送信されます。
sender認証のために使われるモジュールの名前です。
credentialsauthenticate()か独自の認証バックエンドに渡されたユーザ資格情報を含む、キーワード引数のディクショナリです。'sensitive' パターンのセットに一致する (パスワードを含んだ) 資格情報は、シグナルの一部として明確には送信されません。requestThe
HttpRequestobject, if one was provided toauthenticate().
認証のバックエンドLink to this heading
このセクションでは、Django に付属する認証バックエンドについて詳しく説明します。 使用方法と独自の認証バックエンドの作成方法については、ユーザ認証ガイド の 他の認証ソースのセクション を参照してください。
利用可能な認証バックエンドLink to this heading
以下のバックエンドが django.contrib.auth.backends 内で利用可能です:
- class ModelBackendLink to this definition
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
UserandPermissionsMixin.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.- authenticate(request, username=None, password=None, **kwargs)Link to this definition
Tries to authenticate
usernamewithpasswordby callingUser.check_password. If nousernameis provided, it tries to fetch a username fromkwargsusing the keyCustomUser.USERNAME_FIELD. Returns an authenticated user orNone.requestはHttpRequestで、authenticate()が提供されていない場合Noneとなる可能性があります。(バックエンドでこれを通過するため).
- get_user_permissions(user_obj, obj=None)Link to this definition
Returns the set of permission strings the
user_objhas from their own user permissions. Returns an empty set ifis_anonymousoris_activeisFalse.
- get_group_permissions(user_obj, obj=None)Link to this definition
Returns the set of permission strings the
user_objhas from the permissions of the groups they belong. Returns an empty set ifis_anonymousoris_activeisFalse.
- get_all_permissions(user_obj, obj=None)Link to this definition
Returns the set of permission strings the
user_objhas, including both user permissions and group permissions. Returns an empty set ifis_anonymousoris_activeisFalse.
- has_perm(user_obj, perm, obj=None)Link to this definition
Uses
get_all_permissions()to check ifuser_objhas the permission stringperm. ReturnsFalseif the user is notis_active.
- has_module_perms(user_obj, app_label)Link to this definition
Returns whether the
user_objhas any permissions on the appapp_label.
- user_can_authenticate()Link to this definition
Returns whether the user is allowed to authenticate. To match the behavior of
AuthenticationFormwhichprohibits inactive users from logging in, this method returnsFalsefor users withis_active=False. Custom user models that don't have anis_activefield are allowed.
- class AllowAllUsersModelBackendLink to this definition
Same as
ModelBackendexcept that it doesn't reject inactive users becauseuser_can_authenticate()always returnsTrue.When using this backend, you'll likely want to customize the
AuthenticationFormused by theLoginViewby overriding theconfirm_login_allowed()method as it rejects inactive users.
- class RemoteUserBackendLink to this definition
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_userLink to this definition
TrueorFalse. Determines whether or not a user object is created if not already in the database Defaults toTrue.
- authenticate(request, remote_user)Link to this definition
The username passed as
remote_useris considered trusted. This method simply returns the user object with the given username, creating a new user object ifcreate_unknown_userisTrue.Returns
Noneifcreate_unknown_userisFalseand aUserobject with the given username is not found in the database.requestはHttpRequestで、authenticate()が提供されていない場合Noneとなる可能性があります。(バックエンドでこれを通過するため).
- clean_username(username)Link to this definition
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(user)Link to this definition
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.
- user_can_authenticate()Link to this definition
Returns whether the user is allowed to authenticate. This method returns
Falsefor users withis_active=False. Custom user models that don't have anis_activefield are allowed.
- class AllowAllUsersRemoteUserBackendLink to this definition
Same as
RemoteUserBackendexcept that it doesn't reject inactive users becauseuser_can_authenticatealways returnsTrue.
Utility functionsLink to this heading
- get_user(request)Link to this definition
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.Returns an instance of
AnonymousUserif 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.