doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
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. with_perm() also allows an object to be passed as a parameter, but unlike others methods it returns an empty queryset 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. request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
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.
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 a Permission instance. Returns an empty queryset if no users who have the perm found. If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state. If include_superusers is True (default), the result will include superusers. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend |
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. request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend). | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.authenticate |
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. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.get_all_permissions |
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. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.get_group_permissions |
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. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.get_user_permissions |
has_module_perms(user_obj, app_label)
Returns whether the user_obj has any permissions on the app app_label. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.has_module_perms |
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. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.has_perm |
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. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.user_can_authenticate |
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 a Permission instance. Returns an empty queryset if no users who have the perm found. If is_active is True (default), returns only active users, or if False, returns only inactive users. Use None to return all users irrespective of active state. If include_superusers is True (default), the result will include superusers. | django.ref.contrib.auth#django.contrib.auth.backends.ModelBackend.with_perm |
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 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. request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
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. request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend).
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. | django.ref.contrib.auth#django.contrib.auth.backends.RemoteUserBackend |
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 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. request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend). | django.ref.contrib.auth#django.contrib.auth.backends.RemoteUserBackend.authenticate |
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. | django.ref.contrib.auth#django.contrib.auth.backends.RemoteUserBackend.clean_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. request is an HttpRequest and may be None if it wasn’t provided to authenticate() (which passes it on to the backend). | django.ref.contrib.auth#django.contrib.auth.backends.RemoteUserBackend.configure_user |
create_unknown_user
True or False. Determines whether or not a user object is created if not already in the database Defaults to True. | django.ref.contrib.auth#django.contrib.auth.backends.RemoteUserBackend.create_unknown_user |
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. | django.ref.contrib.auth#django.contrib.auth.backends.RemoteUserBackend.user_can_authenticate |
auth() | django.ref.templates.api#django.contrib.auth.context_processors.auth |
login_required(redirect_field_name='next', login_url=None)
As a shortcut, you can use the convenient login_required() decorator: from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
login_required() does the following: If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example: /accounts/login/?next=/polls/3/. If the user is logged in, execute the view normally. The view code is free to assume the user is logged in. By default, the path that the user should be redirected to upon successful authentication is stored in a query string parameter called "next". If you would prefer to use a different name for this parameter, login_required() takes an optional redirect_field_name parameter: from django.contrib.auth.decorators import login_required
@login_required(redirect_field_name='my_redirect_field')
def my_view(request):
...
Note that if you provide a value to redirect_field_name, you will most likely need to customize your login template as well, since the template context variable which stores the redirect path will use the value of redirect_field_name as its key rather than "next" (the default). login_required() also takes an optional login_url parameter. Example: from django.contrib.auth.decorators import login_required
@login_required(login_url='/accounts/login/')
def my_view(request):
...
Note that if you don’t specify the login_url parameter, you’ll need to ensure that the settings.LOGIN_URL and your login view are properly associated. For example, using the defaults, add the following lines to your URLconf: from django.contrib.auth import views as auth_views
path('accounts/login/', auth_views.LoginView.as_view()),
The settings.LOGIN_URL also accepts view function names and named URL patterns. This allows you to freely remap your login view within your URLconf without having to update the setting. | django.topics.auth.default#django.contrib.auth.decorators.login_required |
permission_required(perm, login_url=None, raise_exception=False)
It’s a relatively common task to check whether a user has a particular permission. For that reason, Django provides a shortcut for that case: the permission_required() decorator.: from django.contrib.auth.decorators import permission_required
@permission_required('polls.add_choice')
def my_view(request):
...
Just like the has_perm() method, permission names take the form "<app label>.<permission codename>" (i.e. polls.add_choice for a permission on a model in the polls application). The decorator may also take an iterable of permissions, in which case the user must have all of the permissions in order to access the view. Note that permission_required() also takes an optional login_url parameter: from django.contrib.auth.decorators import permission_required
@permission_required('polls.add_choice', login_url='/loginpage/')
def my_view(request):
...
As in the login_required() decorator, login_url defaults to settings.LOGIN_URL. If the raise_exception parameter is given, the decorator will raise PermissionDenied, prompting the 403 (HTTP Forbidden) view instead of redirecting to the login page. If you want to use raise_exception but also give your users a chance to login first, you can add the login_required() decorator: from django.contrib.auth.decorators import login_required, permission_required
@login_required
@permission_required('polls.add_choice', raise_exception=True)
def my_view(request):
...
This also avoids a redirect loop when LoginView’s redirect_authenticated_user=True and the logged-in user doesn’t have all of the required permissions. | django.topics.auth.default#django.contrib.auth.decorators.permission_required |
user_passes_test(test_func, login_url=None, redirect_field_name='next')
As a shortcut, you can use the convenient user_passes_test decorator which performs a redirect when the callable returns False: from django.contrib.auth.decorators import user_passes_test
def email_check(user):
return user.email.endswith('@example.com')
@user_passes_test(email_check)
def my_view(request):
...
user_passes_test() takes a required argument: a callable that takes a User object and returns True if the user is allowed to view the page. Note that user_passes_test() does not automatically check that the User is not anonymous. user_passes_test() takes two optional arguments:
login_url Lets you specify the URL that users who don’t pass the test will be redirected to. It may be a login page and defaults to settings.LOGIN_URL if you don’t specify one.
redirect_field_name Same as for login_required(). Setting it to None removes it from the URL, which you may want to do if you are redirecting users that don’t pass the test to a non-login page where there’s no “next page”. For example: @user_passes_test(email_check, login_url='/login/')
def my_view(request):
... | django.topics.auth.default#django.contrib.auth.decorators.user_passes_test |
class AdminPasswordChangeForm
A form used in the admin interface to change a user’s password. Takes the user as the first positional argument. | django.topics.auth.default#django.contrib.auth.forms.AdminPasswordChangeForm |
class AuthenticationForm
A form for logging a user in. Takes request as its first positional argument, which is stored on the form instance for use by sub-classes.
confirm_login_allowed(user)
By default, AuthenticationForm rejects users whose is_active flag is set to False. You may override this behavior with a custom policy to determine which users can log in. Do this with a custom form that subclasses AuthenticationForm and overrides the confirm_login_allowed() method. This method should raise a ValidationError if the given user may not log in. For example, to allow all users to log in regardless of “active” status: from django.contrib.auth.forms import AuthenticationForm
class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
def confirm_login_allowed(self, user):
pass
(In this case, you’ll also need to use an authentication backend that allows inactive users, such as AllowAllUsersModelBackend.) Or to allow only some active users to log in: class PickyAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.is_active:
raise ValidationError(
_("This account is inactive."),
code='inactive',
)
if user.username.startswith('b'):
raise ValidationError(
_("Sorry, accounts starting with 'b' aren't welcome here."),
code='no_b_users',
) | django.topics.auth.default#django.contrib.auth.forms.AuthenticationForm |
confirm_login_allowed(user)
By default, AuthenticationForm rejects users whose is_active flag is set to False. You may override this behavior with a custom policy to determine which users can log in. Do this with a custom form that subclasses AuthenticationForm and overrides the confirm_login_allowed() method. This method should raise a ValidationError if the given user may not log in. For example, to allow all users to log in regardless of “active” status: from django.contrib.auth.forms import AuthenticationForm
class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
def confirm_login_allowed(self, user):
pass
(In this case, you’ll also need to use an authentication backend that allows inactive users, such as AllowAllUsersModelBackend.) Or to allow only some active users to log in: class PickyAuthenticationForm(AuthenticationForm):
def confirm_login_allowed(self, user):
if not user.is_active:
raise ValidationError(
_("This account is inactive."),
code='inactive',
)
if user.username.startswith('b'):
raise ValidationError(
_("Sorry, accounts starting with 'b' aren't welcome here."),
code='no_b_users',
) | django.topics.auth.default#django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed |
class PasswordChangeForm
A form for allowing a user to change their password. | django.topics.auth.default#django.contrib.auth.forms.PasswordChangeForm |
class PasswordResetForm
A form for generating and emailing a one-time use link to reset a user’s password.
send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
Uses the arguments to send an EmailMultiAlternatives. Can be overridden to customize how the email is sent to the user.
Parameters:
subject_template_name – the template for the subject.
email_template_name – the template for the email body.
context – context passed to the subject_template, email_template, and html_email_template (if it is not None).
from_email – the sender’s email.
to_email – the email of the requester.
html_email_template_name – the template for the HTML body; defaults to None, in which case a plain text email is sent. By default, save() populates the context with the same variables that PasswordResetView passes to its email context. | django.topics.auth.default#django.contrib.auth.forms.PasswordResetForm |
send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)
Uses the arguments to send an EmailMultiAlternatives. Can be overridden to customize how the email is sent to the user.
Parameters:
subject_template_name – the template for the subject.
email_template_name – the template for the email body.
context – context passed to the subject_template, email_template, and html_email_template (if it is not None).
from_email – the sender’s email.
to_email – the email of the requester.
html_email_template_name – the template for the HTML body; defaults to None, in which case a plain text email is sent. By default, save() populates the context with the same variables that PasswordResetView passes to its email context. | django.topics.auth.default#django.contrib.auth.forms.PasswordResetForm.send_mail |
class SetPasswordForm
A form that lets a user change their password without entering the old password. | django.topics.auth.default#django.contrib.auth.forms.SetPasswordForm |
class UserChangeForm
A form used in the admin interface to change a user’s information and permissions. | django.topics.auth.default#django.contrib.auth.forms.UserChangeForm |
class UserCreationForm
A ModelForm for creating a new user. It has three fields: username (from the user model), password1, and password2. It verifies that password1 and password2 match, validates the password using validate_password(), and sets the user’s password using set_password(). | django.topics.auth.default#django.contrib.auth.forms.UserCreationForm |
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. | django.ref.contrib.auth#django.contrib.auth.get_user |
get_user_model()
Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise. When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example: from django.conf import settings
from django.db import models
class Article(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
When connecting to signals sent by the user model, you should specify the custom model using the AUTH_USER_MODEL setting. For example: from django.conf import settings
from django.db.models.signals import post_save
def post_save_receiver(sender, instance, created, **kwargs):
pass
post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)
Generally speaking, it’s easiest to refer to the user model with the AUTH_USER_MODEL setting in code that’s executed at import time, however, it’s also possible to call get_user_model() while Django is importing models, so you could use models.ForeignKey(get_user_model(), ...). If your app is tested with multiple user models, using @override_settings(AUTH_USER_MODEL=...) for example, and you cache the result of get_user_model() in a module-level variable, you may need to listen to the setting_changed signal to clear the cache. For example: from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.signals import setting_changed
from django.dispatch import receiver
@receiver(setting_changed)
def user_model_swapped(**kwargs):
if kwargs['setting'] == 'AUTH_USER_MODEL':
apps.clear_cache()
from myapp import some_module
some_module.UserModel = get_user_model() | django.topics.auth.customizing#django.contrib.auth.get_user_model |
check_password(password, encoded)
If you’d like to manually authenticate a user by comparing a plain-text password to the hashed password in the database, use the convenience function check_password(). It takes two arguments: the plain-text password to check, and the full value of a user’s password field in the database to check against, and returns True if they match, False otherwise. | django.topics.auth.passwords#django.contrib.auth.hashers.check_password |
is_password_usable(encoded_password)
Returns False if the password is a result of User.set_unusable_password(). | django.topics.auth.passwords#django.contrib.auth.hashers.is_password_usable |
make_password(password, salt=None, hasher='default')
Creates a hashed password in the format used by this application. It takes one mandatory argument: the password in plain-text (string or bytes). Optionally, you can provide a salt and a hashing algorithm to use, if you don’t want to use the defaults (first entry of PASSWORD_HASHERS setting). See Included hashers for the algorithm name of each hasher. If the password argument is None, an unusable password is returned (one that will never be accepted by check_password()). | django.topics.auth.passwords#django.contrib.auth.hashers.make_password |
is_active
Returns True if the user account is currently active. | django.topics.auth.customizing#django.contrib.auth.is_active |
is_staff
Returns True if the user is allowed to have access to the admin site. | django.topics.auth.customizing#django.contrib.auth.is_staff |
login(request, user, backend=None)
To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework. Note that any data set during the anonymous session is retained in the session after a user logs in. This example shows how you might use both authenticate() and login(): from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
... | django.topics.auth.default#django.contrib.auth.login |
logout(request)
To log out a user who has been logged in via django.contrib.auth.login(), use django.contrib.auth.logout() within your view. It takes an HttpRequest object and has no return value. Example: from django.contrib.auth import logout
def logout_view(request):
logout(request)
# Redirect to a success page.
Note that logout() doesn’t throw any errors if the user wasn’t logged in. When you call logout(), the session data for the current request is completely cleaned out. All existing data is removed. This is to prevent another person from using the same web browser to log in and have access to the previous user’s session data. If you want to put anything into the session that will be available to the user immediately after logging out, do that after calling django.contrib.auth.logout(). | django.topics.auth.default#django.contrib.auth.logout |
class AuthenticationMiddleware | django.ref.middleware#django.contrib.auth.middleware.AuthenticationMiddleware |
class PersistentRemoteUserMiddleware | django.ref.middleware#django.contrib.auth.middleware.PersistentRemoteUserMiddleware |
class RemoteUserMiddleware | django.ref.middleware#django.contrib.auth.middleware.RemoteUserMiddleware |
class AccessMixin
login_url
Default return value for get_login_url(). Defaults to None in which case get_login_url() falls back to settings.LOGIN_URL.
permission_denied_message
Default return value for get_permission_denied_message(). Defaults to an empty string.
redirect_field_name
Default return value for get_redirect_field_name(). Defaults to "next".
raise_exception
If this attribute is set to True, a PermissionDenied exception is raised when the conditions are not met. When False (the default), anonymous users are redirected to the login page.
get_login_url()
Returns the URL that users who don’t pass the test will be redirected to. Returns login_url if set, or settings.LOGIN_URL otherwise.
get_permission_denied_message()
When raise_exception is True, this method can be used to control the error message passed to the error handler for display to the user. Returns the permission_denied_message attribute by default.
get_redirect_field_name()
Returns the name of the query parameter that will contain the URL the user should be redirected to after a successful login. If you set this to None, a query parameter won’t be added. Returns the redirect_field_name attribute by default.
handle_no_permission()
Depending on the value of raise_exception, the method either raises a PermissionDenied exception or redirects the user to the login_url, optionally including the redirect_field_name if it is set. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin |
get_login_url()
Returns the URL that users who don’t pass the test will be redirected to. Returns login_url if set, or settings.LOGIN_URL otherwise. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.get_login_url |
get_permission_denied_message()
When raise_exception is True, this method can be used to control the error message passed to the error handler for display to the user. Returns the permission_denied_message attribute by default. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.get_permission_denied_message |
get_redirect_field_name()
Returns the name of the query parameter that will contain the URL the user should be redirected to after a successful login. If you set this to None, a query parameter won’t be added. Returns the redirect_field_name attribute by default. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.get_redirect_field_name |
handle_no_permission()
Depending on the value of raise_exception, the method either raises a PermissionDenied exception or redirects the user to the login_url, optionally including the redirect_field_name if it is set. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.handle_no_permission |
login_url
Default return value for get_login_url(). Defaults to None in which case get_login_url() falls back to settings.LOGIN_URL. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.login_url |
permission_denied_message
Default return value for get_permission_denied_message(). Defaults to an empty string. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.permission_denied_message |
raise_exception
If this attribute is set to True, a PermissionDenied exception is raised when the conditions are not met. When False (the default), anonymous users are redirected to the login page. | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.raise_exception |
redirect_field_name
Default return value for get_redirect_field_name(). Defaults to "next". | django.topics.auth.default#django.contrib.auth.mixins.AccessMixin.redirect_field_name |
class LoginRequiredMixin
If a view is using this mixin, all requests by non-authenticated users will be redirected to the login page or shown an HTTP 403 Forbidden error, depending on the raise_exception parameter. You can set any of the parameters of AccessMixin to customize the handling of unauthorized users: from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to' | django.topics.auth.default#django.contrib.auth.mixins.LoginRequiredMixin |
class PermissionRequiredMixin
This mixin, just like the permission_required decorator, checks whether the user accessing a view has all given permissions. You should specify the permission (or an iterable of permissions) using the permission_required parameter: from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View):
permission_required = 'polls.add_choice'
# Or multiple of permissions:
permission_required = ('polls.view_choice', 'polls.change_choice')
You can set any of the parameters of AccessMixin to customize the handling of unauthorized users. You may also override these methods:
get_permission_required()
Returns an iterable of permission names used by the mixin. Defaults to the permission_required attribute, converted to a tuple if necessary.
has_permission()
Returns a boolean denoting whether the current user has permission to execute the decorated view. By default, this returns the result of calling has_perms() with the list of permissions returned by get_permission_required(). | django.topics.auth.default#django.contrib.auth.mixins.PermissionRequiredMixin |
get_permission_required()
Returns an iterable of permission names used by the mixin. Defaults to the permission_required attribute, converted to a tuple if necessary. | django.topics.auth.default#django.contrib.auth.mixins.PermissionRequiredMixin.get_permission_required |
has_permission()
Returns a boolean denoting whether the current user has permission to execute the decorated view. By default, this returns the result of calling has_perms() with the list of permissions returned by get_permission_required(). | django.topics.auth.default#django.contrib.auth.mixins.PermissionRequiredMixin.has_permission |
class UserPassesTestMixin
When using class-based views, you can use the UserPassesTestMixin to do this.
test_func()
You have to override the test_func() method of the class to provide the test that is performed. Furthermore, you can set any of the parameters of AccessMixin to customize the handling of unauthorized users: from django.contrib.auth.mixins import UserPassesTestMixin
class MyView(UserPassesTestMixin, View):
def test_func(self):
return self.request.user.email.endswith('@example.com')
get_test_func()
You can also override the get_test_func() method to have the mixin use a differently named function for its checks (instead of test_func()).
Stacking UserPassesTestMixin Due to the way UserPassesTestMixin is implemented, you cannot stack them in your inheritance list. The following does NOT work: class TestMixin1(UserPassesTestMixin):
def test_func(self):
return self.request.user.email.endswith('@example.com')
class TestMixin2(UserPassesTestMixin):
def test_func(self):
return self.request.user.username.startswith('django')
class MyView(TestMixin1, TestMixin2, View):
...
If TestMixin1 would call super() and take that result into account, TestMixin1 wouldn’t work standalone anymore. | django.topics.auth.default#django.contrib.auth.mixins.UserPassesTestMixin |
get_test_func()
You can also override the get_test_func() method to have the mixin use a differently named function for its checks (instead of test_func()). | django.topics.auth.default#django.contrib.auth.mixins.UserPassesTestMixin.get_test_func |
test_func()
You have to override the test_func() method of the class to provide the test that is performed. Furthermore, you can set any of the parameters of AccessMixin to customize the handling of unauthorized users: from django.contrib.auth.mixins import UserPassesTestMixin
class MyView(UserPassesTestMixin, View):
def test_func(self):
return self.request.user.email.endswith('@example.com') | django.topics.auth.default#django.contrib.auth.mixins.UserPassesTestMixin.test_func |
class models.AbstractBaseUser
get_username()
Returns the value of the field nominated by USERNAME_FIELD.
clean()
Normalizes the username by calling normalize_username(). If you override this method, be sure to call super() to retain the normalization.
classmethod get_email_field_name()
Returns the name of the email field specified by the EMAIL_FIELD attribute. Defaults to 'email' if EMAIL_FIELD isn’t specified.
classmethod normalize_username(username)
Applies NFKC Unicode normalization to usernames so that visually identical characters with different Unicode code points are considered identical.
is_authenticated
Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance.
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.
set_password(raw_password)
Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the AbstractBaseUser 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)
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.)
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 AbstractBaseUser object. You may need this if authentication for your application takes place against an existing external source such as an LDAP directory.
has_usable_password()
Returns False if set_unusable_password() has been called for this user.
get_session_auth_hash()
Returns an HMAC of the password field. Used for Session invalidation on password change. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser |
check_password(raw_password)
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.) | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.check_password |
clean()
Normalizes the username by calling normalize_username(). If you override this method, be sure to call super() to retain the normalization. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.clean |
get_session_auth_hash()
Returns an HMAC of the password field. Used for Session invalidation on password change. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash |
get_username()
Returns the value of the field nominated by USERNAME_FIELD. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.get_username |
has_usable_password()
Returns False if set_unusable_password() has been called for this user. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.has_usable_password |
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. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.is_anonymous |
is_authenticated
Read-only attribute which is always True (as opposed to AnonymousUser.is_authenticated which is always False). This is a way to tell if the user has been authenticated. This does not imply any permissions and doesn’t check if the user is active or has a valid session. Even though normally you will check this attribute on request.user to find out whether it has been populated by the AuthenticationMiddleware (representing the currently logged-in user), you should know this attribute is True for any User instance. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.is_authenticated |
set_password(raw_password)
Sets the user’s password to the given raw string, taking care of the password hashing. Doesn’t save the AbstractBaseUser object. When the raw_password is None, the password will be set to an unusable password, as if set_unusable_password() were used. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.set_password |
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 AbstractBaseUser object. You may need this if authentication for your application takes place against an existing external source such as an LDAP directory. | django.topics.auth.customizing#django.contrib.auth.models.AbstractBaseUser.set_unusable_password |
class models.AbstractUser
clean()
Normalizes the email by calling BaseUserManager.normalize_email(). If you override this method, be sure to call super() to retain the normalization. | django.topics.auth.customizing#django.contrib.auth.models.AbstractUser |
clean()
Normalizes the email by calling BaseUserManager.normalize_email(). If you override this method, be sure to call super() to retain the normalization. | django.topics.auth.customizing#django.contrib.auth.models.AbstractUser.clean |
class models.AnonymousUser
django.contrib.auth.models.AnonymousUser is a class that implements the django.contrib.auth.models.User interface, with these differences:
id is always None.
username is always the empty string.
get_username() always returns the empty string.
is_anonymous is True instead of False.
is_authenticated is False instead of True.
is_staff and is_superuser are always False.
is_active is always False.
groups and user_permissions are always empty.
set_password(), check_password(), save() and delete() raise NotImplementedError. | django.ref.contrib.auth#django.contrib.auth.models.AnonymousUser |
class models.BaseUserManager
classmethod normalize_email(email)
Normalizes email addresses by lowercasing the domain portion of the email address.
get_by_natural_key(username)
Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD.
make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
Returns a random password with the given length and given string of allowed characters. Note that the default value of allowed_chars doesn’t contain letters that can cause user confusion, including:
i, l, I, and 1 (lowercase letter i, lowercase letter L, uppercase letter i, and the number one)
o, O, and 0 (lowercase letter o, uppercase letter o, and zero) | django.topics.auth.customizing#django.contrib.auth.models.BaseUserManager |
get_by_natural_key(username)
Retrieves a user instance using the contents of the field nominated by USERNAME_FIELD. | django.topics.auth.customizing#django.contrib.auth.models.BaseUserManager.get_by_natural_key |
make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
Returns a random password with the given length and given string of allowed characters. Note that the default value of allowed_chars doesn’t contain letters that can cause user confusion, including:
i, l, I, and 1 (lowercase letter i, lowercase letter L, uppercase letter i, and the number one)
o, O, and 0 (lowercase letter o, uppercase letter o, and zero) | django.topics.auth.customizing#django.contrib.auth.models.BaseUserManager.make_random_password |
class models.CustomUser
USERNAME_FIELD
A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition), unless you use a custom authentication backend that can support non-unique usernames. In the following example, the field identifier is used as the identifying field: class MyUser(AbstractBaseUser):
identifier = models.CharField(max_length=40, unique=True)
...
USERNAME_FIELD = 'identifier'
EMAIL_FIELD
A string describing the name of the email field on the User model. This value is returned by get_email_field_name().
REQUIRED_FIELDS
A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin. For example, here is the partial definition for a user model that defines two required fields - a date of birth and height: class MyUser(AbstractBaseUser):
...
date_of_birth = models.DateField()
height = models.FloatField()
...
REQUIRED_FIELDS = ['date_of_birth', 'height']
Note REQUIRED_FIELDS must contain all required fields on your user model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
is_active
A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on AbstractBaseUser defaulting to True. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the is_active attribute on the built-in
user model for details.
get_full_name()
Optional. A longer formal identifier for the user such as their full name. If implemented, this appears alongside the username in an object’s history in django.contrib.admin.
get_short_name()
Optional. A short, informal identifier for the user such as their first name. If implemented, this replaces the username in the greeting to the user in the header of django.contrib.admin.
Importing AbstractBaseUser AbstractBaseUser and BaseUserManager are importable from django.contrib.auth.base_user so that they can be imported without including django.contrib.auth in INSTALLED_APPS. | django.topics.auth.customizing#django.contrib.auth.models.CustomUser |
EMAIL_FIELD
A string describing the name of the email field on the User model. This value is returned by get_email_field_name(). | django.topics.auth.customizing#django.contrib.auth.models.CustomUser.EMAIL_FIELD |
get_full_name()
Optional. A longer formal identifier for the user such as their full name. If implemented, this appears alongside the username in an object’s history in django.contrib.admin. | django.topics.auth.customizing#django.contrib.auth.models.CustomUser.get_full_name |
get_short_name()
Optional. A short, informal identifier for the user such as their first name. If implemented, this replaces the username in the greeting to the user in the header of django.contrib.admin. | django.topics.auth.customizing#django.contrib.auth.models.CustomUser.get_short_name |
is_active
A boolean attribute that indicates whether the user is considered “active”. This attribute is provided as an attribute on AbstractBaseUser defaulting to True. How you choose to implement it will depend on the details of your chosen auth backends. See the documentation of the is_active attribute on the built-in
user model for details. | django.topics.auth.customizing#django.contrib.auth.models.CustomUser.is_active |
REQUIRED_FIELDS
A list of the field names that will be prompted for when creating a user via the createsuperuser management command. The user will be prompted to supply a value for each of these fields. It must include any field for which blank is False or undefined and may include additional fields you want prompted for when a user is created interactively. REQUIRED_FIELDS has no effect in other parts of Django, like creating a user in the admin. For example, here is the partial definition for a user model that defines two required fields - a date of birth and height: class MyUser(AbstractBaseUser):
...
date_of_birth = models.DateField()
height = models.FloatField()
...
REQUIRED_FIELDS = ['date_of_birth', 'height']
Note REQUIRED_FIELDS must contain all required fields on your user model, but should not contain the USERNAME_FIELD or password as these fields will always be prompted for. | django.topics.auth.customizing#django.contrib.auth.models.CustomUser.REQUIRED_FIELDS |
USERNAME_FIELD
A string describing the name of the field on the user model that is used as the unique identifier. This will usually be a username of some kind, but it can also be an email address, or any other unique identifier. The field must be unique (i.e., have unique=True set in its definition), unless you use a custom authentication backend that can support non-unique usernames. In the following example, the field identifier is used as the identifying field: class MyUser(AbstractBaseUser):
identifier = models.CharField(max_length=40, unique=True)
...
USERNAME_FIELD = 'identifier' | django.topics.auth.customizing#django.contrib.auth.models.CustomUser.USERNAME_FIELD |
class models.CustomUserManager
create_user(username_field, password=None, **other_fields)
The prototype of create_user() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_user should be defined as: def create_user(self, email, date_of_birth, password=None):
# create user here
...
create_superuser(username_field, password=None, **other_fields)
The prototype of create_superuser() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_superuser should be defined as: def create_superuser(self, email, date_of_birth, password=None):
# create superuser here
... | django.topics.auth.customizing#django.contrib.auth.models.CustomUserManager |
create_superuser(username_field, password=None, **other_fields)
The prototype of create_superuser() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_superuser should be defined as: def create_superuser(self, email, date_of_birth, password=None):
# create superuser here
... | django.topics.auth.customizing#django.contrib.auth.models.CustomUserManager.create_superuser |
create_user(username_field, password=None, **other_fields)
The prototype of create_user() should accept the username field, plus all required fields as arguments. For example, if your user model uses email as the username field, and has date_of_birth as a required field, then create_user should be defined as: def create_user(self, email, date_of_birth, password=None):
# create user here
... | django.topics.auth.customizing#django.contrib.auth.models.CustomUserManager.create_user |
class models.Group | django.ref.contrib.auth#django.contrib.auth.models.Group |
name
Required. 150 characters or fewer. Any characters are permitted. Example: 'Awesome Users'. | django.ref.contrib.auth#django.contrib.auth.models.Group.name |
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() | django.ref.contrib.auth#django.contrib.auth.models.Group.permissions |
class models.Permission | django.ref.contrib.auth#django.contrib.auth.models.Permission |
codename
Required. 100 characters or fewer. Example: 'can_vote'. | django.ref.contrib.auth#django.contrib.auth.models.Permission.codename |
content_type
Required. A reference to the django_content_type database table, which contains a record for each installed model. | django.ref.contrib.auth#django.contrib.auth.models.Permission.content_type |
name
Required. 255 characters or fewer. Example: 'Can vote'. | django.ref.contrib.auth#django.contrib.auth.models.Permission.name |
class models.PermissionsMixin
is_superuser
Boolean. Designates that this user has all permissions without explicitly assigning them.
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)
Returns a set of permission strings that the user has, through their groups. If obj is passed in, only returns the group permissions for this specific object.
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 permissions). If User.is_active and is_superuser are both True, this method always returns True. 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 User.is_active and is_superuser are both True, this method always returns True. 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)
Returns True if the user has any permissions in the given package (the Django app label). If User.is_active and is_superuser are both True, this method always returns True. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin |
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. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.get_all_permissions |
get_group_permissions(obj=None)
Returns a set of permission strings that the user has, through their groups. If obj is passed in, only returns the group permissions for this specific object. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.get_group_permissions |
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. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.get_user_permissions |
has_module_perms(package_name)
Returns True if the user has any permissions in the given package (the Django app label). If User.is_active and is_superuser are both True, this method always returns True. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.has_module_perms |
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 permissions). If User.is_active and is_superuser are both True, this method always returns True. If obj is passed in, this method won’t check for a permission for the model, but for this specific object. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.has_perm |
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 User.is_active and is_superuser are both True, this method always returns True. If obj is passed in, this method won’t check for permissions for the model, but for the specific object. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.has_perms |
is_superuser
Boolean. Designates that this user has all permissions without explicitly assigning them. | django.topics.auth.customizing#django.contrib.auth.models.PermissionsMixin.is_superuser |
class models.User | django.ref.contrib.auth#django.contrib.auth.models.User |
check_password(raw_password)
Returns True if the given raw string is the correct password for the user. (This takes care of the password hashing in making the comparison.) | django.ref.contrib.auth#django.contrib.auth.models.User.check_password |
date_joined
A datetime designating when the account was created. Is set to the current date/time by default when the account is created. | django.ref.contrib.auth#django.contrib.auth.models.User.date_joined |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.