| 1 |
====================================== |
| 2 |
Using the Django authentication system |
| 3 |
====================================== |
| 4 |
|
| 5 |
.. currentmodule:: django.contrib.auth |
| 6 |
|
| 7 |
This document explains the usage of Django's authentication system in its |
| 8 |
default configuration. This configuration has evolved to serve the most common |
| 9 |
project needs, handling a reasonably wide range of tasks, and has a careful |
| 10 |
implementation of passwords and permissions. For projects where authentication |
| 11 |
needs differ from the default, Django supports extensive :doc:`extension and |
| 12 |
customization </topics/auth/customizing>` of authentication. |
| 13 |
|
| 14 |
Django authentication provides both authentication and authorization together |
| 15 |
and is generally referred to as the authentication system, as these features |
| 16 |
are somewhat coupled. |
| 17 |
|
| 18 |
.. _user-objects: |
| 19 |
|
| 20 |
``User`` objects |
| 21 |
================ |
| 22 |
|
| 23 |
:class:`~django.contrib.auth.models.User` objects are the core of the |
| 24 |
authentication system. They typically represent the people interacting with |
| 25 |
your site and are used to enable things like restricting access, registering |
| 26 |
user profiles, associating content with creators etc. Only one class of user |
| 27 |
exists in Django's authentication framework, i.e., :attr:`'superusers' |
| 28 |
<django.contrib.auth.models.User.is_superuser>` or admin :attr:`'staff' |
| 29 |
<django.contrib.auth.models.User.is_staff>` users are just user objects with |
| 30 |
special attributes set, not different classes of user objects. |
| 31 |
|
| 32 |
The primary attributes of the default user are: |
| 33 |
|
| 34 |
* :attr:`~django.contrib.auth.models.User.username` |
| 35 |
* :attr:`~django.contrib.auth.models.User.password` |
| 36 |
* :attr:`~django.contrib.auth.models.User.email` |
| 37 |
* :attr:`~django.contrib.auth.models.User.first_name` |
| 38 |
* :attr:`~django.contrib.auth.models.User.last_name` |
| 39 |
|
| 40 |
See the :class:`full API documentation <django.contrib.auth.models.User>` for |
| 41 |
full reference, the documentation that follows is more task oriented. |
| 42 |
|
| 43 |
.. _topics-auth-creating-users: |
| 44 |
|
| 45 |
Creating users |
| 46 |
-------------- |
| 47 |
|
| 48 |
The most direct way to create users is to use the included |
| 49 |
:meth:`~django.contrib.auth.models.UserManager.create_user` helper function: |
| 50 |
|
| 51 |
.. code-block:: pycon |
| 52 |
|
| 53 |
>>> from django.contrib.auth.models import User |
| 54 |
>>> user = User.objects.create_user("john", "[email protected]", "johnpassword") |
| 55 |
|
| 56 |
# At this point, user is a User object that has already been saved |
| 57 |
# to the database. You can continue to change its attributes |
| 58 |
# if you want to change other fields. |
| 59 |
>>> user.last_name = "Lennon" |
| 60 |
>>> user.save() |
| 61 |
|
| 62 |
If you have the Django admin installed, you can also :ref:`create users |
| 63 |
interactively <auth-admin>`. |
| 64 |
|
| 65 |
.. _topics-auth-creating-superusers: |
| 66 |
|
| 67 |
Creating superusers |
| 68 |
------------------- |
| 69 |
|
| 70 |
Create superusers using the :djadmin:`createsuperuser` command: |
| 71 |
|
| 72 |
.. console:: |
| 73 |
|
| 74 |
$ python manage.py createsuperuser --username=joe [email protected] |
| 75 |
|
| 76 |
You will be prompted for a password. After you enter one, the user will be |
| 77 |
created immediately. If you leave off the :option:`--username <createsuperuser |
| 78 |
--username>` or :option:`--email <createsuperuser --email>` options, it will |
| 79 |
prompt you for those values. |
| 80 |
|
| 81 |
Changing passwords |
| 82 |
------------------ |
| 83 |
|
| 84 |
Django does not store raw (clear text) passwords on the user model, but only |
| 85 |
a hash (see :doc:`documentation of how passwords are managed |
| 86 |
</topics/auth/passwords>` for full details). Because of this, do not attempt to |
| 87 |
manipulate the password attribute of the user directly. This is why a helper |
| 88 |
function is used when creating a user. |
| 89 |
|
| 90 |
To change a user's password, you have several options: |
| 91 |
|
| 92 |
:djadmin:`manage.py changepassword *username* <changepassword>` offers a method |
| 93 |
of changing a user's password from the command line. It prompts you to |
| 94 |
change the password of a given user which you must enter twice. If |
| 95 |
they both match, the new password will be changed immediately. If you |
| 96 |
do not supply a user, the command will attempt to change the password |
| 97 |
whose username matches the current system user. |
| 98 |
|
| 99 |
You can also change a password programmatically, using |
| 100 |
:meth:`~django.contrib.auth.models.User.set_password()`: |
| 101 |
|
| 102 |
.. code-block:: pycon |
| 103 |
|
| 104 |
>>> from django.contrib.auth.models import User |
| 105 |
>>> u = User.objects.get(username="john") |
| 106 |
>>> u.set_password("new password") |
| 107 |
>>> u.save() |
| 108 |
|
| 109 |
If you have the Django admin installed, you can also change user's passwords |
| 110 |
on the :ref:`authentication system's admin pages <auth-admin>`. |
| 111 |
|
| 112 |
Django also provides :ref:`views <built-in-auth-views>` and :ref:`forms |
| 113 |
<built-in-auth-forms>` that may be used to allow users to change their own |
| 114 |
passwords. |
| 115 |
|
| 116 |
Changing a user's password will log out all their sessions. See |
| 117 |
:ref:`session-invalidation-on-password-change` for details. |
| 118 |
|
| 119 |
Authenticating users |
| 120 |
-------------------- |
| 121 |
|
| 122 |
.. function:: authenticate(request=None, **credentials) |
| 123 |
.. function:: aauthenticate(request=None, **credentials) |
| 124 |
|
| 125 |
*Asynchronous version*: ``aauthenticate()`` |
| 126 |
|
| 127 |
Use :func:`~django.contrib.auth.authenticate()` to verify a set of |
| 128 |
credentials. It takes credentials as keyword arguments, ``username`` and |
| 129 |
``password`` for the default case, checks them against each |
| 130 |
:ref:`authentication backend <authentication-backends>`, and returns a |
| 131 |
:class:`~django.contrib.auth.models.User` object if the credentials are |
| 132 |
valid for a backend. If the credentials aren't valid for any backend or if |
| 133 |
a backend raises :class:`~django.core.exceptions.PermissionDenied`, it |
| 134 |
returns ``None``. For example:: |
| 135 |
|
| 136 |
from django.contrib.auth import authenticate |
| 137 |
|
| 138 |
user = authenticate(username="john", password="secret") |
| 139 |
if user is not None: |
| 140 |
# A backend authenticated the credentials |
| 141 |
... |
| 142 |
else: |
| 143 |
# No backend authenticated the credentials |
| 144 |
... |
| 145 |
|
| 146 |
``request`` is an optional :class:`~django.http.HttpRequest` which is |
| 147 |
passed on the ``authenticate()`` method of the authentication backends. |
| 148 |
|
| 149 |
.. note:: |
| 150 |
|
| 151 |
This is a low level way to authenticate a set of credentials; for |
| 152 |
example, it's used by the |
| 153 |
:class:`~django.contrib.auth.middleware.RemoteUserMiddleware`. Unless |
| 154 |
you are writing your own authentication system, you probably won't use |
| 155 |
this. Rather if you're looking for a way to login a user, use the |
| 156 |
:class:`~django.contrib.auth.views.LoginView`. |
| 157 |
|
| 158 |
.. _topic-authorization: |
| 159 |
|
| 160 |
Permissions and Authorization |
| 161 |
============================= |
| 162 |
|
| 163 |
Django comes with a built-in permissions system. It provides a way to assign |
| 164 |
permissions to specific users and groups of users. |
| 165 |
|
| 166 |
It's used by the Django admin site, but you're welcome to use it in your own |
| 167 |
code. |
| 168 |
|
| 169 |
The Django admin site uses permissions as follows: |
| 170 |
|
| 171 |
* Access to view objects is limited to users with the "view" or "change" |
| 172 |
permission for that type of object. |
| 173 |
* Access to view the "add" form and add an object is limited to users with |
| 174 |
the "add" permission for that type of object. |
| 175 |
* Access to view the change list, view the "change" form and change an |
| 176 |
object is limited to users with the "change" permission for that type of |
| 177 |
object. |
| 178 |
* Access to delete an object is limited to users with the "delete" |
| 179 |
permission for that type of object. |
| 180 |
|
| 181 |
Permissions can be set not only per type of object, but also per specific |
| 182 |
object instance. By using the |
| 183 |
:meth:`~django.contrib.admin.ModelAdmin.has_view_permission`, |
| 184 |
:meth:`~django.contrib.admin.ModelAdmin.has_add_permission`, |
| 185 |
:meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and |
| 186 |
:meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided |
| 187 |
by the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to |
| 188 |
customize permissions for different object instances of the same type. |
| 189 |
|
| 190 |
:class:`~django.contrib.auth.models.User` objects have two many-to-many |
| 191 |
fields: ``groups`` and ``user_permissions``. |
| 192 |
:class:`~django.contrib.auth.models.User` objects can access their related |
| 193 |
objects in the same way as any other :doc:`Django model |
| 194 |
</topics/db/models>`:: |
| 195 |
|
| 196 |
myuser.groups.set([group_list]) |
| 197 |
myuser.groups.add(group, group, ...) |
| 198 |
myuser.groups.remove(group, group, ...) |
| 199 |
myuser.groups.clear() |
| 200 |
myuser.user_permissions.set([permission_list]) |
| 201 |
myuser.user_permissions.add(permission, permission, ...) |
| 202 |
myuser.user_permissions.remove(permission, permission, ...) |
| 203 |
myuser.user_permissions.clear() |
| 204 |
|
| 205 |
Default permissions |
| 206 |
------------------- |
| 207 |
|
| 208 |
When ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS` |
| 209 |
setting, it will ensure that four default permissions -- add, change, delete, |
| 210 |
and view -- are created for each Django model defined in one of your installed |
| 211 |
applications. |
| 212 |
|
| 213 |
These permissions will be created when you run :djadmin:`manage.py migrate |
| 214 |
<migrate>`; the first time you run ``migrate`` after adding |
| 215 |
``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions |
| 216 |
will be created for all previously-installed models, as well as for any new |
| 217 |
models being installed at that time. Afterward, it will create default |
| 218 |
permissions for new models each time you run :djadmin:`manage.py migrate |
| 219 |
<migrate>` (the function that creates permissions is connected to the |
| 220 |
:data:`~django.db.models.signals.post_migrate` signal). |
| 221 |
|
| 222 |
Assuming you have an application with an |
| 223 |
:attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``, |
| 224 |
to test for basic permissions you should use: |
| 225 |
|
| 226 |
* add: ``user.has_perm('foo.add_bar')`` |
| 227 |
* change: ``user.has_perm('foo.change_bar')`` |
| 228 |
* delete: ``user.has_perm('foo.delete_bar')`` |
| 229 |
* view: ``user.has_perm('foo.view_bar')`` |
| 230 |
|
| 231 |
The :class:`~django.contrib.auth.models.Permission` model is rarely accessed |
| 232 |
directly. |
| 233 |
|
| 234 |
Groups |
| 235 |
------ |
| 236 |
|
| 237 |
:class:`django.contrib.auth.models.Group` models are a generic way of |
| 238 |
categorizing users so you can apply permissions, or some other label, to those |
| 239 |
users. A user can belong to any number of groups. |
| 240 |
|
| 241 |
A user in a group automatically has the permissions granted to that group. For |
| 242 |
example, if the group ``Site editors`` has the permission |
| 243 |
``can_edit_home_page``, any user in that group will have that permission. |
| 244 |
|
| 245 |
Beyond permissions, groups are a convenient way to categorize users to give |
| 246 |
them some label, or extended functionality. For example, you could create a |
| 247 |
group ``'Special users'``, and you could write code that could, say, give them |
| 248 |
access to a members-only portion of your site, or send them members-only email |
| 249 |
messages. |
| 250 |
|
| 251 |
Programmatically creating permissions |
| 252 |
------------------------------------- |
| 253 |
|
| 254 |
While :ref:`custom permissions <custom-permissions>` can be defined within |
| 255 |
a model's ``Meta`` class, you can also create permissions directly. For |
| 256 |
example, you can create the ``can_publish`` permission for a ``BlogPost`` model |
| 257 |
in ``myapp``:: |
| 258 |
|
| 259 |
from myapp.models import BlogPost |
| 260 |
from django.contrib.auth.models import Permission |
| 261 |
from django.contrib.contenttypes.models import ContentType |
| 262 |
|
| 263 |
content_type = ContentType.objects.get_for_model(BlogPost) |
| 264 |
permission = Permission.objects.create( |
| 265 |
codename="can_publish", |
| 266 |
name="Can Publish Posts", |
| 267 |
content_type=content_type, |
| 268 |
) |
| 269 |
|
| 270 |
The permission can then be assigned to a |
| 271 |
:class:`~django.contrib.auth.models.User` via its ``user_permissions`` |
| 272 |
attribute or to a :class:`~django.contrib.auth.models.Group` via its |
| 273 |
``permissions`` attribute. |
| 274 |
|
| 275 |
.. admonition:: Proxy models need their own content type |
| 276 |
|
| 277 |
If you want to create :ref:`permissions for a proxy model |
| 278 |
<proxy-models-permissions-topic>`, pass ``for_concrete_model=False`` to |
| 279 |
:meth:`.ContentTypeManager.get_for_model` to get the appropriate |
| 280 |
``ContentType``:: |
| 281 |
|
| 282 |
content_type = ContentType.objects.get_for_model( |
| 283 |
BlogPostProxy, for_concrete_model=False |
| 284 |
) |
| 285 |
|
| 286 |
Permission caching |
| 287 |
------------------ |
| 288 |
|
| 289 |
The :class:`~django.contrib.auth.backends.ModelBackend` caches permissions on |
| 290 |
the user object after the first time they need to be fetched for a permissions |
| 291 |
check. This is typically fine for the request-response cycle since permissions |
| 292 |
aren't typically checked immediately after they are added (in the admin, for |
| 293 |
example). If you are adding permissions and checking them immediately |
| 294 |
afterward, in a test or view for example, the easiest solution is to re-fetch |
| 295 |
the user from the database. For example:: |
| 296 |
|
| 297 |
from django.contrib.auth.models import Permission, User |
| 298 |
from django.contrib.contenttypes.models import ContentType |
| 299 |
from django.shortcuts import get_object_or_404 |
| 300 |
|
| 301 |
from myapp.models import BlogPost |
| 302 |
|
| 303 |
|
| 304 |
def user_gains_perms(request, user_id): |
| 305 |
user = get_object_or_404(User, pk=user_id) |
| 306 |
# any permission check will cache the current set of permissions |
| 307 |
user.has_perm("myapp.change_blogpost") |
| 308 |
|
| 309 |
content_type = ContentType.objects.get_for_model(BlogPost) |
| 310 |
permission = Permission.objects.get( |
| 311 |
codename="change_blogpost", |
| 312 |
content_type=content_type, |
| 313 |
) |
| 314 |
user.user_permissions.add(permission) |
| 315 |
|
| 316 |
# Checking the cached permission set |
| 317 |
user.has_perm("myapp.change_blogpost") # False |
| 318 |
|
| 319 |
# Request new instance of User |
| 320 |
# Be aware that user.refresh_from_db() won't clear the cache. |
| 321 |
user = get_object_or_404(User, pk=user_id) |
| 322 |
|
| 323 |
# Permission cache is repopulated from the database |
| 324 |
user.has_perm("myapp.change_blogpost") # True |
| 325 |
|
| 326 |
... |
| 327 |
|
| 328 |
.. _proxy-models-permissions-topic: |
| 329 |
|
| 330 |
Proxy models |
| 331 |
------------ |
| 332 |
|
| 333 |
Proxy models work exactly the same way as concrete models. Permissions are |
| 334 |
created using the own content type of the proxy model. Proxy models don't |
| 335 |
inherit the permissions of the concrete model they subclass:: |
| 336 |
|
| 337 |
class Person(models.Model): |
| 338 |
class Meta: |
| 339 |
permissions = [("can_eat_pizzas", "Can eat pizzas")] |
| 340 |
|
| 341 |
|
| 342 |
class Student(Person): |
| 343 |
class Meta: |
| 344 |
proxy = True |
| 345 |
permissions = [("can_deliver_pizzas", "Can deliver pizzas")] |
| 346 |
|
| 347 |
.. code-block:: pycon |
| 348 |
|
| 349 |
>>> # Fetch the content type for the proxy model. |
| 350 |
>>> content_type = ContentType.objects.get_for_model(Student, for_concrete_model=False) |
| 351 |
>>> student_permissions = Permission.objects.filter(content_type=content_type) |
| 352 |
>>> [p.codename for p in student_permissions] |
| 353 |
['add_student', 'change_student', 'delete_student', 'view_student', |
| 354 |
'can_deliver_pizzas'] |
| 355 |
>>> for permission in student_permissions: |
| 356 |
... user.user_permissions.add(permission) |
| 357 |
... |
| 358 |
>>> user.has_perm("app.add_person") |
| 359 |
False |
| 360 |
>>> user.has_perm("app.can_eat_pizzas") |
| 361 |
False |
| 362 |
>>> user.has_perms(("app.add_student", "app.can_deliver_pizzas")) |
| 363 |
True |
| 364 |
|
| 365 |
.. _auth-web-requests: |
| 366 |
|
| 367 |
Authentication in web requests |
| 368 |
============================== |
| 369 |
|
| 370 |
Django uses :doc:`sessions </topics/http/sessions>` and middleware to hook the |
| 371 |
authentication system into :class:`request objects <django.http.HttpRequest>`. |
| 372 |
|
| 373 |
These provide a :attr:`request.user <django.http.HttpRequest.user>` attribute |
| 374 |
and a :meth:`request.auser <django.http.HttpRequest.auser>` async method |
| 375 |
on every request which represents the current user. If the current user has not |
| 376 |
logged in, this attribute will be set to an instance |
| 377 |
of :class:`~django.contrib.auth.models.AnonymousUser`, otherwise it will be an |
| 378 |
instance of :class:`~django.contrib.auth.models.User`. |
| 379 |
|
| 380 |
You can tell them apart with |
| 381 |
:attr:`~django.contrib.auth.models.User.is_authenticated`, like so:: |
| 382 |
|
| 383 |
if request.user.is_authenticated: |
| 384 |
# Do something for authenticated users. |
| 385 |
... |
| 386 |
else: |
| 387 |
# Do something for anonymous users. |
| 388 |
... |
| 389 |
|
| 390 |
Or in an asynchronous view:: |
| 391 |
|
| 392 |
user = await request.auser() |
| 393 |
if user.is_authenticated: |
| 394 |
# Do something for authenticated users. |
| 395 |
... |
| 396 |
else: |
| 397 |
# Do something for anonymous users. |
| 398 |
... |
| 399 |
|
| 400 |
.. _how-to-log-a-user-in: |
| 401 |
|
| 402 |
How to log a user in |
| 403 |
-------------------- |
| 404 |
|
| 405 |
If you have an authenticated user you want to attach to the current session |
| 406 |
- this is done with a :func:`~django.contrib.auth.login` function. |
| 407 |
|
| 408 |
.. function:: login(request, user, backend=None) |
| 409 |
.. function:: alogin(request, user, backend=None) |
| 410 |
|
| 411 |
*Asynchronous version*: ``alogin()`` |
| 412 |
|
| 413 |
To log a user in, from a view, use :func:`~django.contrib.auth.login()`. It |
| 414 |
takes an :class:`~django.http.HttpRequest` object and a |
| 415 |
:class:`~django.contrib.auth.models.User` object. |
| 416 |
:func:`~django.contrib.auth.login()` saves the user's ID in the session, |
| 417 |
using Django's session framework. |
| 418 |
|
| 419 |
Note that any data set during the anonymous session is retained in the |
| 420 |
session after a user logs in. |
| 421 |
|
| 422 |
This example shows how you might use both |
| 423 |
:func:`~django.contrib.auth.authenticate()` and |
| 424 |
:func:`~django.contrib.auth.login()`:: |
| 425 |
|
| 426 |
from django.contrib.auth import authenticate, login |
| 427 |
|
| 428 |
|
| 429 |
def my_view(request): |
| 430 |
username = request.POST["username"] |
| 431 |
password = request.POST["password"] |
| 432 |
user = authenticate(request, username=username, password=password) |
| 433 |
if user is not None: |
| 434 |
login(request, user) |
| 435 |
# Redirect to a success page. |
| 436 |
... |
| 437 |
else: |
| 438 |
# Return an 'invalid login' error message. |
| 439 |
... |
| 440 |
|
| 441 |
Selecting the authentication backend |
| 442 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 443 |
|
| 444 |
When a user logs in, the user's ID and the backend that was used for |
| 445 |
authentication are saved in the user's session. This allows the same |
| 446 |
:ref:`authentication backend <authentication-backends>` to fetch the user's |
| 447 |
details on a future request. The authentication backend to save in the session |
| 448 |
is selected as follows: |
| 449 |
|
| 450 |
#. Use the value of the optional ``backend`` argument, if provided. |
| 451 |
#. Use the value of the ``user.backend`` attribute, if present. This allows |
| 452 |
pairing :func:`~django.contrib.auth.authenticate()` and |
| 453 |
:func:`~django.contrib.auth.login()`: |
| 454 |
:func:`~django.contrib.auth.authenticate()` |
| 455 |
sets the ``user.backend`` attribute on the user object it returns. |
| 456 |
#. Use the ``backend`` in :setting:`AUTHENTICATION_BACKENDS`, if there is only |
| 457 |
one. |
| 458 |
#. Otherwise, raise an exception. |
| 459 |
|
| 460 |
In cases 1 and 2, the value of the ``backend`` argument or the ``user.backend`` |
| 461 |
attribute should be a dotted import path string (like that found in |
| 462 |
:setting:`AUTHENTICATION_BACKENDS`), not the actual backend class. |
| 463 |
|
| 464 |
How to log a user out |
| 465 |
--------------------- |
| 466 |
|
| 467 |
.. function:: logout(request) |
| 468 |
.. function:: alogout(request) |
| 469 |
|
| 470 |
*Asynchronous version*: ``alogout()`` |
| 471 |
|
| 472 |
To log out a user who has been logged in via |
| 473 |
:func:`django.contrib.auth.login()`, use |
| 474 |
:func:`django.contrib.auth.logout()` within your view. It takes an |
| 475 |
:class:`~django.http.HttpRequest` object and has no return value. |
| 476 |
Example:: |
| 477 |
|
| 478 |
from django.contrib.auth import logout |
| 479 |
|
| 480 |
|
| 481 |
def logout_view(request): |
| 482 |
logout(request) |
| 483 |
# Redirect to a success page. |
| 484 |
|
| 485 |
Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if |
| 486 |
the user wasn't logged in. |
| 487 |
|
| 488 |
When you call :func:`~django.contrib.auth.logout()`, the session data for |
| 489 |
the current request is completely cleaned out. All existing data is |
| 490 |
removed. This is to prevent another person from using the same web browser |
| 491 |
to log in and have access to the previous user's session data. If you want |
| 492 |
to put anything into the session that will be available to the user |
| 493 |
immediately after logging out, do that *after* calling |
| 494 |
:func:`django.contrib.auth.logout()`. |
| 495 |
|
| 496 |
Limiting access to logged-in users |
| 497 |
---------------------------------- |
| 498 |
|
| 499 |
The raw way |
| 500 |
~~~~~~~~~~~ |
| 501 |
|
| 502 |
The raw way to limit access to pages is to check |
| 503 |
:attr:`request.user.is_authenticated |
| 504 |
<django.contrib.auth.models.User.is_authenticated>` and either redirect to a |
| 505 |
login page:: |
| 506 |
|
| 507 |
from django.conf import settings |
| 508 |
from django.shortcuts import redirect |
| 509 |
|
| 510 |
|
| 511 |
def my_view(request): |
| 512 |
if not request.user.is_authenticated: |
| 513 |
return redirect(f"{settings.LOGIN_URL}?next={request.path}") |
| 514 |
# ... |
| 515 |
|
| 516 |
...or display an error message:: |
| 517 |
|
| 518 |
from django.shortcuts import render |
| 519 |
|
| 520 |
|
| 521 |
def my_view(request): |
| 522 |
if not request.user.is_authenticated: |
| 523 |
return render(request, "myapp/login_error.html") |
| 524 |
# ... |
| 525 |
|
| 526 |
.. currentmodule:: django.contrib.auth.decorators |
| 527 |
|
| 528 |
The ``login_required`` decorator |
| 529 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 530 |
|
| 531 |
.. function:: login_required(redirect_field_name='next', login_url=None) |
| 532 |
|
| 533 |
As a shortcut, you can use the convenient |
| 534 |
:func:`~django.contrib.auth.decorators.login_required` decorator:: |
| 535 |
|
| 536 |
from django.contrib.auth.decorators import login_required |
| 537 |
|
| 538 |
|
| 539 |
@login_required |
| 540 |
def my_view(request): ... |
| 541 |
|
| 542 |
:func:`~django.contrib.auth.decorators.login_required` does the following: |
| 543 |
|
| 544 |
* If the user isn't logged in, redirect to |
| 545 |
:setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute |
| 546 |
path in the query string. Example: ``/accounts/login/?next=/polls/3/``. |
| 547 |
|
| 548 |
* If the user is logged in, execute the view normally. The view code is |
| 549 |
free to assume the user is logged in. |
| 550 |
|
| 551 |
By default, the path that the user should be redirected to upon |
| 552 |
successful authentication is stored in a query string parameter called |
| 553 |
``"next"``. If you would prefer to use a different name for this parameter, |
| 554 |
:func:`~django.contrib.auth.decorators.login_required` takes an |
| 555 |
optional ``redirect_field_name`` parameter:: |
| 556 |
|
| 557 |
from django.contrib.auth.decorators import login_required |
| 558 |
|
| 559 |
|
| 560 |
@login_required(redirect_field_name="my_redirect_field") |
| 561 |
def my_view(request): ... |
| 562 |
|
| 563 |
Note that if you provide a value to ``redirect_field_name``, you will most |
| 564 |
likely need to customize your login template as well, since the template |
| 565 |
context variable which stores the redirect path will use the value of |
| 566 |
``redirect_field_name`` as its key rather than ``"next"`` (the default). |
| 567 |
|
| 568 |
:func:`~django.contrib.auth.decorators.login_required` also takes an |
| 569 |
optional ``login_url`` parameter. Example:: |
| 570 |
|
| 571 |
from django.contrib.auth.decorators import login_required |
| 572 |
|
| 573 |
|
| 574 |
@login_required(login_url="/accounts/login/") |
| 575 |
def my_view(request): ... |
| 576 |
|
| 577 |
Note that if you don't specify the ``login_url`` parameter, you'll need to |
| 578 |
ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login |
| 579 |
view are properly associated. For example, using the defaults, add the |
| 580 |
following lines to your URLconf:: |
| 581 |
|
| 582 |
from django.contrib.auth import views as auth_views |
| 583 |
|
| 584 |
path("accounts/login/", auth_views.LoginView.as_view()), |
| 585 |
|
| 586 |
The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts view function |
| 587 |
names and :ref:`named URL patterns <naming-url-patterns>`. This allows you |
| 588 |
to freely remap your login view within your URLconf without having to |
| 589 |
update the setting. |
| 590 |
|
| 591 |
.. note:: |
| 592 |
|
| 593 |
The ``login_required`` decorator does NOT check the ``is_active`` flag on a |
| 594 |
user, but the default :setting:`AUTHENTICATION_BACKENDS` reject inactive |
| 595 |
users. |
| 596 |
|
| 597 |
.. seealso:: |
| 598 |
|
| 599 |
If you are writing custom views for Django's admin (or need the same |
| 600 |
authorization check that the built-in views use), you may find the |
| 601 |
:func:`django.contrib.admin.views.decorators.staff_member_required` |
| 602 |
decorator a useful alternative to ``login_required()``. |
| 603 |
|
| 604 |
.. versionchanged:: 5.1 |
| 605 |
|
| 606 |
Support for wrapping asynchronous view functions was added. |
| 607 |
|
| 608 |
.. currentmodule:: django.contrib.auth.mixins |
| 609 |
|
| 610 |
The ``LoginRequiredMixin`` mixin |
| 611 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 612 |
|
| 613 |
When using :doc:`class-based views </topics/class-based-views/index>`, you can |
| 614 |
achieve the same behavior as with ``login_required`` by using the |
| 615 |
``LoginRequiredMixin``. This mixin should be at the leftmost position in the |
| 616 |
inheritance list. |
| 617 |
|
| 618 |
.. class:: LoginRequiredMixin |
| 619 |
|
| 620 |
If a view is using this mixin, all requests by non-authenticated users will |
| 621 |
be redirected to the login page or shown an HTTP 403 Forbidden error, |
| 622 |
depending on the |
| 623 |
:attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` parameter. |
| 624 |
|
| 625 |
You can set any of the parameters of |
| 626 |
:class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling |
| 627 |
of unauthorized users:: |
| 628 |
|
| 629 |
|
| 630 |
from django.contrib.auth.mixins import LoginRequiredMixin |
| 631 |
|
| 632 |
|
| 633 |
class MyView(LoginRequiredMixin, View): |
| 634 |
login_url = "/login/" |
| 635 |
redirect_field_name = "redirect_to" |
| 636 |
|
| 637 |
.. note:: |
| 638 |
|
| 639 |
Just as the ``login_required`` decorator, this mixin does NOT check the |
| 640 |
``is_active`` flag on a user, but the default |
| 641 |
:setting:`AUTHENTICATION_BACKENDS` reject inactive users. |
| 642 |
|
| 643 |
.. _disable-login-required-middleware-for-views: |
| 644 |
|
| 645 |
.. currentmodule:: django.contrib.auth.decorators |
| 646 |
|
| 647 |
The ``login_not_required`` decorator |
| 648 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 649 |
|
| 650 |
.. versionadded:: 5.1 |
| 651 |
|
| 652 |
When :class:`~django.contrib.auth.middleware.LoginRequiredMiddleware` is |
| 653 |
installed, all views require authentication by default. Some views, such as the |
| 654 |
login view, may need to disable this behavior. |
| 655 |
|
| 656 |
.. function:: login_not_required() |
| 657 |
|
| 658 |
Allows unauthenticated requests to this view when |
| 659 |
:class:`~django.contrib.auth.middleware.LoginRequiredMiddleware` is |
| 660 |
installed. |
| 661 |
|
| 662 |
Limiting access to logged-in users that pass a test |
| 663 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 664 |
|
| 665 |
To limit access based on certain permissions or some other test, you'd do |
| 666 |
essentially the same thing as described in the previous section. |
| 667 |
|
| 668 |
You can run your test on :attr:`request.user <django.http.HttpRequest.user>` in |
| 669 |
the view directly. For example, this view checks to make sure the user has an |
| 670 |
email in the desired domain and if not, redirects to the login page:: |
| 671 |
|
| 672 |
from django.shortcuts import redirect |
| 673 |
|
| 674 |
|
| 675 |
def my_view(request): |
| 676 |
if not request.user.email.endswith("@example.com"): |
| 677 |
return redirect("/login/?next=%s" % request.path) |
| 678 |
# ... |
| 679 |
|
| 680 |
.. function:: user_passes_test(test_func, login_url=None, redirect_field_name='next') |
| 681 |
|
| 682 |
As a shortcut, you can use the convenient ``user_passes_test`` decorator |
| 683 |
which performs a redirect when the callable returns ``False``:: |
| 684 |
|
| 685 |
from django.contrib.auth.decorators import user_passes_test |
| 686 |
|
| 687 |
|
| 688 |
def email_check(user): |
| 689 |
return user.email.endswith("@example.com") |
| 690 |
|
| 691 |
|
| 692 |
@user_passes_test(email_check) |
| 693 |
def my_view(request): ... |
| 694 |
|
| 695 |
:func:`~django.contrib.auth.decorators.user_passes_test` takes a required |
| 696 |
argument: a callable that takes a |
| 697 |
:class:`~django.contrib.auth.models.User` object and returns ``True`` if |
| 698 |
the user is allowed to view the page. Note that |
| 699 |
:func:`~django.contrib.auth.decorators.user_passes_test` does not |
| 700 |
automatically check that the :class:`~django.contrib.auth.models.User` is |
| 701 |
not anonymous. |
| 702 |
|
| 703 |
:func:`~django.contrib.auth.decorators.user_passes_test` takes two |
| 704 |
optional arguments: |
| 705 |
|
| 706 |
``login_url`` |
| 707 |
Lets you specify the URL that users who don't pass the test will be |
| 708 |
redirected to. It may be a login page and defaults to |
| 709 |
:setting:`settings.LOGIN_URL <LOGIN_URL>` if you don't specify one. |
| 710 |
|
| 711 |
``redirect_field_name`` |
| 712 |
Same as for :func:`~django.contrib.auth.decorators.login_required`. |
| 713 |
Setting it to ``None`` removes it from the URL, which you may want to do |
| 714 |
if you are redirecting users that don't pass the test to a non-login |
| 715 |
page where there's no "next page". |
| 716 |
|
| 717 |
For example:: |
| 718 |
|
| 719 |
@user_passes_test(email_check, login_url="/login/") |
| 720 |
def my_view(request): ... |
| 721 |
|
| 722 |
.. versionchanged:: 5.1 |
| 723 |
|
| 724 |
Support for wrapping asynchronous view functions and using asynchronous |
| 725 |
test callables was added. |
| 726 |
|
| 727 |
.. currentmodule:: django.contrib.auth.mixins |
| 728 |
|
| 729 |
.. class:: UserPassesTestMixin |
| 730 |
|
| 731 |
When using :doc:`class-based views </topics/class-based-views/index>`, you |
| 732 |
can use the ``UserPassesTestMixin`` to do this. |
| 733 |
|
| 734 |
.. method:: test_func() |
| 735 |
|
| 736 |
You have to override the ``test_func()`` method of the class to |
| 737 |
provide the test that is performed. Furthermore, you can set any of the |
| 738 |
parameters of :class:`~django.contrib.auth.mixins.AccessMixin` to |
| 739 |
customize the handling of unauthorized users:: |
| 740 |
|
| 741 |
from django.contrib.auth.mixins import UserPassesTestMixin |
| 742 |
|
| 743 |
|
| 744 |
class MyView(UserPassesTestMixin, View): |
| 745 |
def test_func(self): |
| 746 |
return self.request.user.email.endswith("@example.com") |
| 747 |
|
| 748 |
.. method:: get_test_func() |
| 749 |
|
| 750 |
You can also override the ``get_test_func()`` method to have the mixin |
| 751 |
use a differently named function for its checks (instead of |
| 752 |
:meth:`test_func`). |
| 753 |
|
| 754 |
.. admonition:: Stacking ``UserPassesTestMixin`` |
| 755 |
|
| 756 |
Due to the way ``UserPassesTestMixin`` is implemented, you cannot stack |
| 757 |
them in your inheritance list. The following does NOT work:: |
| 758 |
|
| 759 |
class TestMixin1(UserPassesTestMixin): |
| 760 |
def test_func(self): |
| 761 |
return self.request.user.email.endswith("@example.com") |
| 762 |
|
| 763 |
|
| 764 |
class TestMixin2(UserPassesTestMixin): |
| 765 |
def test_func(self): |
| 766 |
return self.request.user.username.startswith("django") |
| 767 |
|
| 768 |
|
| 769 |
class MyView(TestMixin1, TestMixin2, View): ... |
| 770 |
|
| 771 |
If ``TestMixin1`` would call ``super()`` and take that result into |
| 772 |
account, ``TestMixin1`` wouldn't work standalone anymore. |
| 773 |
|
| 774 |
.. currentmodule:: django.contrib.auth.decorators |
| 775 |
|
| 776 |
The ``permission_required`` decorator |
| 777 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 778 |
|
| 779 |
.. function:: permission_required(perm, login_url=None, raise_exception=False) |
| 780 |
|
| 781 |
It's a relatively common task to check whether a user has a particular |
| 782 |
permission. For that reason, Django provides a shortcut for that case: the |
| 783 |
:func:`~django.contrib.auth.decorators.permission_required()` decorator:: |
| 784 |
|
| 785 |
from django.contrib.auth.decorators import permission_required |
| 786 |
|
| 787 |
|
| 788 |
@permission_required("polls.add_choice") |
| 789 |
def my_view(request): ... |
| 790 |
|
| 791 |
Just like the :meth:`~django.contrib.auth.models.User.has_perm` method, |
| 792 |
permission names take the form ``"<app label>.<permission codename>"`` |
| 793 |
(i.e. ``polls.add_choice`` for a permission on a model in the ``polls`` |
| 794 |
application). |
| 795 |
|
| 796 |
The decorator may also take an iterable of permissions, in which case the |
| 797 |
user must have all of the permissions in order to access the view. |
| 798 |
|
| 799 |
Note that :func:`~django.contrib.auth.decorators.permission_required()` |
| 800 |
also takes an optional ``login_url`` parameter:: |
| 801 |
|
| 802 |
from django.contrib.auth.decorators import permission_required |
| 803 |
|
| 804 |
|
| 805 |
@permission_required("polls.add_choice", login_url="/loginpage/") |
| 806 |
def my_view(request): ... |
| 807 |
|
| 808 |
As in the :func:`~django.contrib.auth.decorators.login_required` decorator, |
| 809 |
``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`. |
| 810 |
|
| 811 |
If the ``raise_exception`` parameter is given, the decorator will raise |
| 812 |
:exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403 |
| 813 |
(HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the |
| 814 |
login page. |
| 815 |
|
| 816 |
If you want to use ``raise_exception`` but also give your users a chance to |
| 817 |
login first, you can add the |
| 818 |
:func:`~django.contrib.auth.decorators.login_required` decorator:: |
| 819 |
|
| 820 |
from django.contrib.auth.decorators import login_required, permission_required |
| 821 |
|
| 822 |
|
| 823 |
@login_required |
| 824 |
@permission_required("polls.add_choice", raise_exception=True) |
| 825 |
def my_view(request): ... |
| 826 |
|
| 827 |
This also avoids a redirect loop when :class:`.LoginView`'s |
| 828 |
``redirect_authenticated_user=True`` and the logged-in user doesn't have |
| 829 |
all of the required permissions. |
| 830 |
|
| 831 |
.. versionchanged:: 5.1 |
| 832 |
|
| 833 |
Support for wrapping asynchronous view functions was added. |
| 834 |
|
| 835 |
.. currentmodule:: django.contrib.auth.mixins |
| 836 |
|
| 837 |
The ``PermissionRequiredMixin`` mixin |
| 838 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 839 |
|
| 840 |
To apply permission checks to :doc:`class-based views |
| 841 |
</ref/class-based-views/index>`, you can use the ``PermissionRequiredMixin``: |
| 842 |
|
| 843 |
.. class:: PermissionRequiredMixin |
| 844 |
|
| 845 |
This mixin, just like the ``permission_required`` |
| 846 |
decorator, checks whether the user accessing a view has all given |
| 847 |
permissions. You should specify the permission (or an iterable of |
| 848 |
permissions) using the ``permission_required`` parameter:: |
| 849 |
|
| 850 |
from django.contrib.auth.mixins import PermissionRequiredMixin |
| 851 |
|
| 852 |
|
| 853 |
class MyView(PermissionRequiredMixin, View): |
| 854 |
permission_required = "polls.add_choice" |
| 855 |
# Or multiple of permissions: |
| 856 |
permission_required = ["polls.view_choice", "polls.change_choice"] |
| 857 |
|
| 858 |
You can set any of the parameters of |
| 859 |
:class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling |
| 860 |
of unauthorized users. |
| 861 |
|
| 862 |
You may also override these methods: |
| 863 |
|
| 864 |
.. method:: get_permission_required() |
| 865 |
|
| 866 |
Returns an iterable of permission names used by the mixin. Defaults to |
| 867 |
the ``permission_required`` attribute, converted to a tuple if |
| 868 |
necessary. |
| 869 |
|
| 870 |
.. method:: has_permission() |
| 871 |
|
| 872 |
Returns a boolean denoting whether the current user has permission to |
| 873 |
execute the decorated view. By default, this returns the result of |
| 874 |
calling :meth:`~django.contrib.auth.models.User.has_perms()` with the |
| 875 |
list of permissions returned by :meth:`get_permission_required()`. |
| 876 |
|
| 877 |
Redirecting unauthorized requests in class-based views |
| 878 |
------------------------------------------------------ |
| 879 |
|
| 880 |
To ease the handling of access restrictions in :doc:`class-based views |
| 881 |
</ref/class-based-views/index>`, the ``AccessMixin`` can be used to configure |
| 882 |
the behavior of a view when access is denied. Authenticated users are denied |
| 883 |
access with an HTTP 403 Forbidden response. Anonymous users are redirected to |
| 884 |
the login page or shown an HTTP 403 Forbidden response, depending on the |
| 885 |
:attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` attribute. |
| 886 |
|
| 887 |
.. class:: AccessMixin |
| 888 |
|
| 889 |
.. attribute:: login_url |
| 890 |
|
| 891 |
Default return value for :meth:`get_login_url`. Defaults to ``None`` |
| 892 |
in which case :meth:`get_login_url` falls back to |
| 893 |
:setting:`settings.LOGIN_URL <LOGIN_URL>`. |
| 894 |
|
| 895 |
.. attribute:: permission_denied_message |
| 896 |
|
| 897 |
Default return value for :meth:`get_permission_denied_message`. |
| 898 |
Defaults to an empty string. |
| 899 |
|
| 900 |
.. attribute:: redirect_field_name |
| 901 |
|
| 902 |
Default return value for :meth:`get_redirect_field_name`. Defaults to |
| 903 |
``"next"``. |
| 904 |
|
| 905 |
.. attribute:: raise_exception |
| 906 |
|
| 907 |
If this attribute is set to ``True``, a |
| 908 |
:class:`~django.core.exceptions.PermissionDenied` exception is raised |
| 909 |
when the conditions are not met. When ``False`` (the default), |
| 910 |
anonymous users are redirected to the login page. |
| 911 |
|
| 912 |
.. method:: get_login_url() |
| 913 |
|
| 914 |
Returns the URL that users who don't pass the test will be redirected |
| 915 |
to. Returns :attr:`login_url` if set, or :setting:`settings.LOGIN_URL |
| 916 |
<LOGIN_URL>` otherwise. |
| 917 |
|
| 918 |
.. method:: get_permission_denied_message() |
| 919 |
|
| 920 |
When :attr:`raise_exception` is ``True``, this method can be used to |
| 921 |
control the error message passed to the error handler for display to |
| 922 |
the user. Returns the :attr:`permission_denied_message` attribute by |
| 923 |
default. |
| 924 |
|
| 925 |
.. method:: get_redirect_field_name() |
| 926 |
|
| 927 |
Returns the name of the query parameter that will contain the URL the |
| 928 |
user should be redirected to after a successful login. If you set this |
| 929 |
to ``None``, a query parameter won't be added. Returns the |
| 930 |
:attr:`redirect_field_name` attribute by default. |
| 931 |
|
| 932 |
.. method:: handle_no_permission() |
| 933 |
|
| 934 |
Depending on the value of ``raise_exception``, the method either raises |
| 935 |
a :exc:`~django.core.exceptions.PermissionDenied` exception or |
| 936 |
redirects the user to the ``login_url``, optionally including the |
| 937 |
``redirect_field_name`` if it is set. |
| 938 |
|
| 939 |
.. currentmodule:: django.contrib.auth |
| 940 |
|
| 941 |
.. _session-invalidation-on-password-change: |
| 942 |
|
| 943 |
Session invalidation on password change |
| 944 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 945 |
|
| 946 |
If your :setting:`AUTH_USER_MODEL` inherits from |
| 947 |
:class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own |
| 948 |
:meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()` |
| 949 |
method, authenticated sessions will include the hash returned by this function. |
| 950 |
In the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an |
| 951 |
HMAC of the password field. Django verifies that the hash in the session for |
| 952 |
each request matches the one that's computed during the request. This allows a |
| 953 |
user to log out all of their sessions by changing their password. |
| 954 |
|
| 955 |
The default password change views included with Django, |
| 956 |
:class:`~django.contrib.auth.views.PasswordChangeView` and the |
| 957 |
``user_change_password`` view in the :mod:`django.contrib.auth` admin, update |
| 958 |
the session with the new password hash so that a user changing their own |
| 959 |
password won't log themselves out. If you have a custom password change view |
| 960 |
and wish to have similar behavior, use the :func:`update_session_auth_hash` |
| 961 |
function. |
| 962 |
|
| 963 |
.. function:: update_session_auth_hash(request, user) |
| 964 |
.. function:: aupdate_session_auth_hash(request, user) |
| 965 |
|
| 966 |
*Asynchronous version*: ``aupdate_session_auth_hash()`` |
| 967 |
|
| 968 |
This function takes the current request and the updated user object from |
| 969 |
which the new session hash will be derived and updates the session hash |
| 970 |
appropriately. It also rotates the session key so that a stolen session |
| 971 |
cookie will be invalidated. |
| 972 |
|
| 973 |
Example usage:: |
| 974 |
|
| 975 |
from django.contrib.auth import update_session_auth_hash |
| 976 |
|
| 977 |
|
| 978 |
def password_change(request): |
| 979 |
if request.method == "POST": |
| 980 |
form = PasswordChangeForm(user=request.user, data=request.POST) |
| 981 |
if form.is_valid(): |
| 982 |
form.save() |
| 983 |
update_session_auth_hash(request, form.user) |
| 984 |
else: |
| 985 |
... |
| 986 |
|
| 987 |
.. note:: |
| 988 |
|
| 989 |
Since |
| 990 |
:meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()` |
| 991 |
is based on :setting:`SECRET_KEY`, secret key values must be |
| 992 |
rotated to avoid invalidating existing sessions when updating your site to |
| 993 |
use a new secret. See :setting:`SECRET_KEY_FALLBACKS` for details. |
| 994 |
|
| 995 |
.. _built-in-auth-views: |
| 996 |
|
| 997 |
Authentication Views |
| 998 |
-------------------- |
| 999 |
|
| 1000 |
.. module:: django.contrib.auth.views |
| 1001 |
|
| 1002 |
Django provides several views that you can use for handling login, logout, and |
| 1003 |
password management. These make use of the :ref:`stock auth forms |
| 1004 |
<built-in-auth-forms>` but you can pass in your own forms as well. |
| 1005 |
|
| 1006 |
Django provides no default template for the authentication views. You should |
| 1007 |
create your own templates for the views you want to use. The template context |
| 1008 |
is documented in each view, see :ref:`all-authentication-views`. |
| 1009 |
|
| 1010 |
.. _using-the-views: |
| 1011 |
|
| 1012 |
Using the views |
| 1013 |
~~~~~~~~~~~~~~~ |
| 1014 |
|
| 1015 |
There are different methods to implement these views in your project. The |
| 1016 |
easiest way is to include the provided URLconf in ``django.contrib.auth.urls`` |
| 1017 |
in your own URLconf, for example:: |
| 1018 |
|
| 1019 |
urlpatterns = [ |
| 1020 |
path("accounts/", include("django.contrib.auth.urls")), |
| 1021 |
] |
| 1022 |
|
| 1023 |
This will include the following URL patterns: |
| 1024 |
|
| 1025 |
.. code-block:: text |
| 1026 |
|
| 1027 |
accounts/login/ [name='login'] |
| 1028 |
accounts/logout/ [name='logout'] |
| 1029 |
accounts/password_change/ [name='password_change'] |
| 1030 |
accounts/password_change/done/ [name='password_change_done'] |
| 1031 |
accounts/password_reset/ [name='password_reset'] |
| 1032 |
accounts/password_reset/done/ [name='password_reset_done'] |
| 1033 |
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm'] |
| 1034 |
accounts/reset/done/ [name='password_reset_complete'] |
| 1035 |
|
| 1036 |
The views provide a URL name for easier reference. See :doc:`the URL |
| 1037 |
documentation </topics/http/urls>` for details on using named URL patterns. |
| 1038 |
|
| 1039 |
If you want more control over your URLs, you can reference a specific view in |
| 1040 |
your URLconf:: |
| 1041 |
|
| 1042 |
from django.contrib.auth import views as auth_views |
| 1043 |
|
| 1044 |
urlpatterns = [ |
| 1045 |
path("change-password/", auth_views.PasswordChangeView.as_view()), |
| 1046 |
] |
| 1047 |
|
| 1048 |
The views have optional arguments you can use to alter the behavior of the |
| 1049 |
view. For example, if you want to change the template name a view uses, you can |
| 1050 |
provide the ``template_name`` argument. A way to do this is to provide keyword |
| 1051 |
arguments in the URLconf, these will be passed on to the view. For example:: |
| 1052 |
|
| 1053 |
urlpatterns = [ |
| 1054 |
path( |
| 1055 |
"change-password/", |
| 1056 |
auth_views.PasswordChangeView.as_view(template_name="change-password.html"), |
| 1057 |
), |
| 1058 |
] |
| 1059 |
|
| 1060 |
All views are :doc:`class-based </topics/class-based-views/index>`, which allows |
| 1061 |
you to easily customize them by subclassing. |
| 1062 |
|
| 1063 |
.. _all-authentication-views: |
| 1064 |
|
| 1065 |
All authentication views |
| 1066 |
~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1067 |
|
| 1068 |
This is a list with all the views ``django.contrib.auth`` provides. For |
| 1069 |
implementation details see :ref:`using-the-views`. |
| 1070 |
|
| 1071 |
.. class:: LoginView |
| 1072 |
|
| 1073 |
**URL name:** ``login`` |
| 1074 |
|
| 1075 |
See :doc:`the URL documentation </topics/http/urls>` for details on using |
| 1076 |
named URL patterns. |
| 1077 |
|
| 1078 |
**Methods and Attributes** |
| 1079 |
|
| 1080 |
.. attribute:: template_name |
| 1081 |
|
| 1082 |
The name of a template to display for the view used to log the user in. |
| 1083 |
Defaults to :file:`registration/login.html`. |
| 1084 |
|
| 1085 |
.. attribute:: next_page |
| 1086 |
|
| 1087 |
The URL to redirect to after login. Defaults to |
| 1088 |
:setting:`LOGIN_REDIRECT_URL`. |
| 1089 |
|
| 1090 |
.. attribute:: redirect_field_name |
| 1091 |
|
| 1092 |
The name of a ``GET`` field containing the URL to redirect to after |
| 1093 |
login. Defaults to ``next``. Overrides the |
| 1094 |
:meth:`get_default_redirect_url` URL if the given ``GET`` parameter is |
| 1095 |
passed. |
| 1096 |
|
| 1097 |
.. attribute:: authentication_form |
| 1098 |
|
| 1099 |
A callable (typically a form class) to use for authentication. Defaults |
| 1100 |
to :class:`~django.contrib.auth.forms.AuthenticationForm`. |
| 1101 |
|
| 1102 |
.. attribute:: extra_context |
| 1103 |
|
| 1104 |
A dictionary of context data that will be added to the default context |
| 1105 |
data passed to the template. |
| 1106 |
|
| 1107 |
.. attribute:: redirect_authenticated_user |
| 1108 |
|
| 1109 |
A boolean that controls whether or not authenticated users accessing |
| 1110 |
the login page will be redirected as if they had just successfully |
| 1111 |
logged in. Defaults to ``False``. |
| 1112 |
|
| 1113 |
.. warning:: |
| 1114 |
|
| 1115 |
If you enable ``redirect_authenticated_user``, other websites will |
| 1116 |
be able to determine if their visitors are authenticated on your |
| 1117 |
site by requesting redirect URLs to image files on your website. To |
| 1118 |
avoid this "`social media fingerprinting |
| 1119 |
<https://robinlinus.github.io/socialmedia-leak/>`_" information |
| 1120 |
leakage, host all images and your favicon on a separate domain. |
| 1121 |
|
| 1122 |
Enabling ``redirect_authenticated_user`` can also result in a |
| 1123 |
redirect loop when using the :func:`.permission_required` decorator |
| 1124 |
unless the ``raise_exception`` parameter is used. |
| 1125 |
|
| 1126 |
.. attribute:: success_url_allowed_hosts |
| 1127 |
|
| 1128 |
A :class:`set` of hosts, in addition to :meth:`request.get_host() |
| 1129 |
<django.http.HttpRequest.get_host>`, that are safe for redirecting |
| 1130 |
after login. Defaults to an empty :class:`set`. |
| 1131 |
|
| 1132 |
.. method:: get_default_redirect_url() |
| 1133 |
|
| 1134 |
Returns the URL to redirect to after login. The default implementation |
| 1135 |
resolves and returns :attr:`next_page` if set, or |
| 1136 |
:setting:`LOGIN_REDIRECT_URL` otherwise. |
| 1137 |
|
| 1138 |
Here's what ``LoginView`` does: |
| 1139 |
|
| 1140 |
* If called via ``GET``, it displays a login form that POSTs to the |
| 1141 |
same URL. More on this in a bit. |
| 1142 |
|
| 1143 |
* If called via ``POST`` with user submitted credentials, it tries to log |
| 1144 |
the user in. If login is successful, the view redirects to the URL |
| 1145 |
specified in ``next``. If ``next`` isn't provided, it redirects to |
| 1146 |
:setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which |
| 1147 |
defaults to ``/accounts/profile/``). If login isn't successful, it |
| 1148 |
redisplays the login form. |
| 1149 |
|
| 1150 |
It's your responsibility to provide the html for the login template |
| 1151 |
, called ``registration/login.html`` by default. This template gets passed |
| 1152 |
four template context variables: |
| 1153 |
|
| 1154 |
* ``form``: A :class:`~django.forms.Form` object representing the |
| 1155 |
:class:`~django.contrib.auth.forms.AuthenticationForm`. |
| 1156 |
|
| 1157 |
* ``next``: The URL to redirect to after successful login. This may |
| 1158 |
contain a query string, too. |
| 1159 |
|
| 1160 |
* ``site``: The current :class:`~django.contrib.sites.models.Site`, |
| 1161 |
according to the :setting:`SITE_ID` setting. If you don't have the |
| 1162 |
site framework installed, this will be set to an instance of |
| 1163 |
:class:`~django.contrib.sites.requests.RequestSite`, which derives the |
| 1164 |
site name and domain from the current |
| 1165 |
:class:`~django.http.HttpRequest`. |
| 1166 |
|
| 1167 |
* ``site_name``: An alias for ``site.name``. If you don't have the site |
| 1168 |
framework installed, this will be set to the value of |
| 1169 |
:attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`. |
| 1170 |
For more on sites, see :doc:`/ref/contrib/sites`. |
| 1171 |
|
| 1172 |
If you'd prefer not to call the template :file:`registration/login.html`, |
| 1173 |
you can pass the ``template_name`` parameter via the extra arguments to |
| 1174 |
the ``as_view`` method in your URLconf. For example, this URLconf line would |
| 1175 |
use :file:`myapp/login.html` instead:: |
| 1176 |
|
| 1177 |
path("accounts/login/", auth_views.LoginView.as_view(template_name="myapp/login.html")), |
| 1178 |
|
| 1179 |
You can also specify the name of the ``GET`` field which contains the URL |
| 1180 |
to redirect to after login using ``redirect_field_name``. By default, the |
| 1181 |
field is called ``next``. |
| 1182 |
|
| 1183 |
Here's a sample :file:`registration/login.html` template you can use as a |
| 1184 |
starting point. It assumes you have a :file:`base.html` template that |
| 1185 |
defines a ``content`` block: |
| 1186 |
|
| 1187 |
.. code-block:: html+django |
| 1188 |
|
| 1189 |
{% extends "base.html" %} |
| 1190 |
|
| 1191 |
{% block content %} |
| 1192 |
|
| 1193 |
{% if form.errors %} |
| 1194 |
<p>Your username and password didn't match. Please try again.</p> |
| 1195 |
{% endif %} |
| 1196 |
|
| 1197 |
{% if next %} |
| 1198 |
{% if user.is_authenticated %} |
| 1199 |
<p>Your account doesn't have access to this page. To proceed, |
| 1200 |
please login with an account that has access.</p> |
| 1201 |
{% else %} |
| 1202 |
<p>Please login to see this page.</p> |
| 1203 |
{% endif %} |
| 1204 |
{% endif %} |
| 1205 |
|
| 1206 |
<form method="post" action="{% url 'login' %}"> |
| 1207 |
{% csrf_token %} |
| 1208 |
<table> |
| 1209 |
<tr> |
| 1210 |
<td>{{ form.username.label_tag }}</td> |
| 1211 |
<td>{{ form.username }}</td> |
| 1212 |
</tr> |
| 1213 |
<tr> |
| 1214 |
<td>{{ form.password.label_tag }}</td> |
| 1215 |
<td>{{ form.password }}</td> |
| 1216 |
</tr> |
| 1217 |
</table> |
| 1218 |
|
| 1219 |
<input type="submit" value="login"> |
| 1220 |
<input type="hidden" name="next" value="{{ next }}"> |
| 1221 |
</form> |
| 1222 |
|
| 1223 |
{# Assumes you set up the password_reset view in your URLconf #} |
| 1224 |
<p><a href="{% url 'password_reset' %}">Lost password?</a></p> |
| 1225 |
|
| 1226 |
{% endblock %} |
| 1227 |
|
| 1228 |
If you have customized authentication (see :doc:`Customizing Authentication |
| 1229 |
</topics/auth/customizing>`) you can use a custom authentication form by |
| 1230 |
setting the ``authentication_form`` attribute. This form must accept a |
| 1231 |
``request`` keyword argument in its ``__init__()`` method and provide a |
| 1232 |
``get_user()`` method which returns the authenticated user object (this |
| 1233 |
method is only ever called after successful form validation). |
| 1234 |
|
| 1235 |
.. class:: LogoutView |
| 1236 |
|
| 1237 |
Logs a user out on ``POST`` requests. |
| 1238 |
|
| 1239 |
**URL name:** ``logout`` |
| 1240 |
|
| 1241 |
**Attributes:** |
| 1242 |
|
| 1243 |
.. attribute:: next_page |
| 1244 |
|
| 1245 |
The URL to redirect to after logout. Defaults to |
| 1246 |
:setting:`LOGOUT_REDIRECT_URL`. |
| 1247 |
|
| 1248 |
.. attribute:: template_name |
| 1249 |
|
| 1250 |
The full name of a template to display after logging the user out. |
| 1251 |
Defaults to :file:`registration/logged_out.html`. |
| 1252 |
|
| 1253 |
.. attribute:: redirect_field_name |
| 1254 |
|
| 1255 |
The name of a ``GET`` field containing the URL to redirect to after log |
| 1256 |
out. Defaults to ``'next'``. Overrides the |
| 1257 |
:attr:`next_page` URL if the given ``GET`` parameter is |
| 1258 |
passed. |
| 1259 |
|
| 1260 |
.. attribute:: extra_context |
| 1261 |
|
| 1262 |
A dictionary of context data that will be added to the default context |
| 1263 |
data passed to the template. |
| 1264 |
|
| 1265 |
.. attribute:: success_url_allowed_hosts |
| 1266 |
|
| 1267 |
A :class:`set` of hosts, in addition to :meth:`request.get_host() |
| 1268 |
<django.http.HttpRequest.get_host>`, that are safe for redirecting |
| 1269 |
after logout. Defaults to an empty :class:`set`. |
| 1270 |
|
| 1271 |
**Template context:** |
| 1272 |
|
| 1273 |
* ``title``: The string "Logged out", localized. |
| 1274 |
|
| 1275 |
* ``site``: The current :class:`~django.contrib.sites.models.Site`, |
| 1276 |
according to the :setting:`SITE_ID` setting. If you don't have the |
| 1277 |
site framework installed, this will be set to an instance of |
| 1278 |
:class:`~django.contrib.sites.requests.RequestSite`, which derives the |
| 1279 |
site name and domain from the current |
| 1280 |
:class:`~django.http.HttpRequest`. |
| 1281 |
|
| 1282 |
* ``site_name``: An alias for ``site.name``. If you don't have the site |
| 1283 |
framework installed, this will be set to the value of |
| 1284 |
:attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`. |
| 1285 |
For more on sites, see :doc:`/ref/contrib/sites`. |
| 1286 |
|
| 1287 |
.. function:: logout_then_login(request, login_url=None) |
| 1288 |
|
| 1289 |
Logs a user out on ``POST`` requests, then redirects to the login page. |
| 1290 |
|
| 1291 |
**URL name:** No default URL provided |
| 1292 |
|
| 1293 |
**Optional arguments:** |
| 1294 |
|
| 1295 |
* ``login_url``: The URL of the login page to redirect to. |
| 1296 |
Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied. |
| 1297 |
|
| 1298 |
.. class:: PasswordChangeView |
| 1299 |
|
| 1300 |
**URL name:** ``password_change`` |
| 1301 |
|
| 1302 |
Allows a user to change their password. |
| 1303 |
|
| 1304 |
**Attributes:** |
| 1305 |
|
| 1306 |
.. attribute:: template_name |
| 1307 |
|
| 1308 |
The full name of a template to use for displaying the password change |
| 1309 |
form. Defaults to :file:`registration/password_change_form.html` if not |
| 1310 |
supplied. |
| 1311 |
|
| 1312 |
.. attribute:: success_url |
| 1313 |
|
| 1314 |
The URL to redirect to after a successful password change. Defaults to |
| 1315 |
``'password_change_done'``. |
| 1316 |
|
| 1317 |
.. attribute:: form_class |
| 1318 |
|
| 1319 |
A custom "change password" form which must accept a ``user`` keyword |
| 1320 |
argument. The form is responsible for actually changing the user's |
| 1321 |
password. Defaults to |
| 1322 |
:class:`~django.contrib.auth.forms.PasswordChangeForm`. |
| 1323 |
|
| 1324 |
.. attribute:: extra_context |
| 1325 |
|
| 1326 |
A dictionary of context data that will be added to the default context |
| 1327 |
data passed to the template. |
| 1328 |
|
| 1329 |
**Template context:** |
| 1330 |
|
| 1331 |
* ``form``: The password change form (see ``form_class`` above). |
| 1332 |
|
| 1333 |
.. class:: PasswordChangeDoneView |
| 1334 |
|
| 1335 |
**URL name:** ``password_change_done`` |
| 1336 |
|
| 1337 |
The page shown after a user has changed their password. |
| 1338 |
|
| 1339 |
**Attributes:** |
| 1340 |
|
| 1341 |
.. attribute:: template_name |
| 1342 |
|
| 1343 |
The full name of a template to use. Defaults to |
| 1344 |
:file:`registration/password_change_done.html` if not supplied. |
| 1345 |
|
| 1346 |
.. attribute:: extra_context |
| 1347 |
|
| 1348 |
A dictionary of context data that will be added to the default context |
| 1349 |
data passed to the template. |
| 1350 |
|
| 1351 |
.. class:: PasswordResetView |
| 1352 |
|
| 1353 |
**URL name:** ``password_reset`` |
| 1354 |
|
| 1355 |
Allows a user to reset their password by generating a one-time use link |
| 1356 |
that can be used to reset the password, and sending that link to the |
| 1357 |
user's registered email address. |
| 1358 |
|
| 1359 |
This view will send an email if the following conditions are met: |
| 1360 |
|
| 1361 |
* The email address provided exists in the system. |
| 1362 |
* The requested user is active (``User.is_active`` is ``True``). |
| 1363 |
* The requested user has a usable password. Users flagged with an unusable |
| 1364 |
password (see |
| 1365 |
:meth:`~django.contrib.auth.models.User.set_unusable_password`) aren't |
| 1366 |
allowed to request a password reset to prevent misuse when using an |
| 1367 |
external authentication source like LDAP. |
| 1368 |
|
| 1369 |
If any of these conditions are *not* met, no email will be sent, but the |
| 1370 |
user won't receive any error message either. This prevents information |
| 1371 |
leaking to potential attackers. If you want to provide an error message in |
| 1372 |
this case, you can subclass |
| 1373 |
:class:`~django.contrib.auth.forms.PasswordResetForm` and use the |
| 1374 |
``form_class`` attribute. |
| 1375 |
|
| 1376 |
.. note:: |
| 1377 |
|
| 1378 |
Be aware that sending an email costs extra time, hence you may be |
| 1379 |
vulnerable to an email address enumeration timing attack due to a |
| 1380 |
difference between the duration of a reset request for an existing |
| 1381 |
email address and the duration of a reset request for a nonexistent |
| 1382 |
email address. To reduce the overhead, you can use a 3rd party package |
| 1383 |
that allows to send emails asynchronously, e.g. :pypi:`django-mailer`. |
| 1384 |
|
| 1385 |
**Attributes:** |
| 1386 |
|
| 1387 |
.. attribute:: template_name |
| 1388 |
|
| 1389 |
The full name of a template to use for displaying the password reset |
| 1390 |
form. Defaults to :file:`registration/password_reset_form.html` if not |
| 1391 |
supplied. |
| 1392 |
|
| 1393 |
.. attribute:: form_class |
| 1394 |
|
| 1395 |
Form that will be used to get the email of the user to reset the |
| 1396 |
password for. Defaults to |
| 1397 |
:class:`~django.contrib.auth.forms.PasswordResetForm`. |
| 1398 |
|
| 1399 |
.. attribute:: email_template_name |
| 1400 |
|
| 1401 |
The full name of a template to use for generating the email with the |
| 1402 |
reset password link. Defaults to |
| 1403 |
:file:`registration/password_reset_email.html` if not supplied. |
| 1404 |
|
| 1405 |
.. attribute:: subject_template_name |
| 1406 |
|
| 1407 |
The full name of a template to use for the subject of the email with |
| 1408 |
the reset password link. Defaults to |
| 1409 |
:file:`registration/password_reset_subject.txt` if not supplied. |
| 1410 |
|
| 1411 |
.. attribute:: token_generator |
| 1412 |
|
| 1413 |
Instance of the class to check the one time link. This will default to |
| 1414 |
``default_token_generator``, it's an instance of |
| 1415 |
``django.contrib.auth.tokens.PasswordResetTokenGenerator``. |
| 1416 |
|
| 1417 |
.. attribute:: success_url |
| 1418 |
|
| 1419 |
The URL to redirect to after a successful password reset request. |
| 1420 |
Defaults to ``'password_reset_done'``. |
| 1421 |
|
| 1422 |
.. attribute:: from_email |
| 1423 |
|
| 1424 |
A valid email address. By default Django uses the |
| 1425 |
:setting:`DEFAULT_FROM_EMAIL`. |
| 1426 |
|
| 1427 |
.. attribute:: extra_context |
| 1428 |
|
| 1429 |
A dictionary of context data that will be added to the default context |
| 1430 |
data passed to the template. |
| 1431 |
|
| 1432 |
.. attribute:: html_email_template_name |
| 1433 |
|
| 1434 |
The full name of a template to use for generating a |
| 1435 |
:mimetype:`text/html` multipart email with the password reset link. By |
| 1436 |
default, HTML email is not sent. |
| 1437 |
|
| 1438 |
.. attribute:: extra_email_context |
| 1439 |
|
| 1440 |
A dictionary of context data that will be available in the email |
| 1441 |
template. It can be used to override default template context values |
| 1442 |
listed below e.g. ``domain``. |
| 1443 |
|
| 1444 |
**Template context:** |
| 1445 |
|
| 1446 |
* ``form``: The form (see ``form_class`` above) for resetting the user's |
| 1447 |
password. |
| 1448 |
|
| 1449 |
**Email template context:** |
| 1450 |
|
| 1451 |
* ``email``: An alias for ``user.email`` |
| 1452 |
|
| 1453 |
* ``user``: The current :class:`~django.contrib.auth.models.User`, |
| 1454 |
according to the ``email`` form field. Only active users are able to |
| 1455 |
reset their passwords (``User.is_active is True``). |
| 1456 |
|
| 1457 |
* ``site_name``: An alias for ``site.name``. If you don't have the site |
| 1458 |
framework installed, this will be set to the value of |
| 1459 |
:attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`. |
| 1460 |
For more on sites, see :doc:`/ref/contrib/sites`. |
| 1461 |
|
| 1462 |
* ``domain``: An alias for ``site.domain``. If you don't have the site |
| 1463 |
framework installed, this will be set to the value of |
| 1464 |
``request.get_host()``. |
| 1465 |
|
| 1466 |
* ``protocol``: http or https |
| 1467 |
|
| 1468 |
* ``uid``: The user's primary key encoded in base 64. |
| 1469 |
|
| 1470 |
* ``token``: Token to check that the reset link is valid. |
| 1471 |
|
| 1472 |
Sample ``registration/password_reset_email.html`` (email body template): |
| 1473 |
|
| 1474 |
.. code-block:: html+django |
| 1475 |
|
| 1476 |
Someone asked for password reset for email {{ email }}. Follow the link below: |
| 1477 |
{{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} |
| 1478 |
|
| 1479 |
The same template context is used for subject template. Subject must be |
| 1480 |
single line plain text string. |
| 1481 |
|
| 1482 |
.. class:: PasswordResetDoneView |
| 1483 |
|
| 1484 |
**URL name:** ``password_reset_done`` |
| 1485 |
|
| 1486 |
The page shown after a user has been emailed a link to reset their |
| 1487 |
password. This view is called by default if the :class:`PasswordResetView` |
| 1488 |
doesn't have an explicit ``success_url`` URL set. |
| 1489 |
|
| 1490 |
.. note:: |
| 1491 |
|
| 1492 |
If the email address provided does not exist in the system, the user is |
| 1493 |
inactive, or has an unusable password, the user will still be |
| 1494 |
redirected to this view but no email will be sent. |
| 1495 |
|
| 1496 |
**Attributes:** |
| 1497 |
|
| 1498 |
.. attribute:: template_name |
| 1499 |
|
| 1500 |
The full name of a template to use. Defaults to |
| 1501 |
:file:`registration/password_reset_done.html` if not supplied. |
| 1502 |
|
| 1503 |
.. attribute:: extra_context |
| 1504 |
|
| 1505 |
A dictionary of context data that will be added to the default context |
| 1506 |
data passed to the template. |
| 1507 |
|
| 1508 |
.. class:: PasswordResetConfirmView |
| 1509 |
|
| 1510 |
**URL name:** ``password_reset_confirm`` |
| 1511 |
|
| 1512 |
Presents a form for entering a new password. |
| 1513 |
|
| 1514 |
**Keyword arguments from the URL:** |
| 1515 |
|
| 1516 |
* ``uidb64``: The user's id encoded in base 64. |
| 1517 |
|
| 1518 |
* ``token``: Token to check that the password is valid. |
| 1519 |
|
| 1520 |
**Attributes:** |
| 1521 |
|
| 1522 |
.. attribute:: template_name |
| 1523 |
|
| 1524 |
The full name of a template to display the confirm password view. |
| 1525 |
Default value is :file:`registration/password_reset_confirm.html`. |
| 1526 |
|
| 1527 |
.. attribute:: token_generator |
| 1528 |
|
| 1529 |
Instance of the class to check the password. This will default to |
| 1530 |
``default_token_generator``, it's an instance of |
| 1531 |
``django.contrib.auth.tokens.PasswordResetTokenGenerator``. |
| 1532 |
|
| 1533 |
.. attribute:: post_reset_login |
| 1534 |
|
| 1535 |
A boolean indicating if the user should be automatically authenticated |
| 1536 |
after a successful password reset. Defaults to ``False``. |
| 1537 |
|
| 1538 |
.. attribute:: post_reset_login_backend |
| 1539 |
|
| 1540 |
A dotted path to the authentication backend to use when authenticating |
| 1541 |
a user if ``post_reset_login`` is ``True``. Required only if you have |
| 1542 |
multiple :setting:`AUTHENTICATION_BACKENDS` configured. Defaults to |
| 1543 |
``None``. |
| 1544 |
|
| 1545 |
.. attribute:: form_class |
| 1546 |
|
| 1547 |
Form that will be used to set the password. Defaults to |
| 1548 |
:class:`~django.contrib.auth.forms.SetPasswordForm`. |
| 1549 |
|
| 1550 |
.. attribute:: success_url |
| 1551 |
|
| 1552 |
URL to redirect after the password reset done. Defaults to |
| 1553 |
``'password_reset_complete'``. |
| 1554 |
|
| 1555 |
.. attribute:: extra_context |
| 1556 |
|
| 1557 |
A dictionary of context data that will be added to the default context |
| 1558 |
data passed to the template. |
| 1559 |
|
| 1560 |
.. attribute:: reset_url_token |
| 1561 |
|
| 1562 |
Token parameter displayed as a component of password reset URLs. |
| 1563 |
Defaults to ``'set-password'``. |
| 1564 |
|
| 1565 |
**Template context:** |
| 1566 |
|
| 1567 |
* ``form``: The form (see ``form_class`` above) for setting the new user's |
| 1568 |
password. |
| 1569 |
|
| 1570 |
* ``validlink``: Boolean, True if the link (combination of ``uidb64`` and |
| 1571 |
``token``) is valid or unused yet. |
| 1572 |
|
| 1573 |
.. class:: PasswordResetCompleteView |
| 1574 |
|
| 1575 |
**URL name:** ``password_reset_complete`` |
| 1576 |
|
| 1577 |
Presents a view which informs the user that the password has been |
| 1578 |
successfully changed. |
| 1579 |
|
| 1580 |
**Attributes:** |
| 1581 |
|
| 1582 |
.. attribute:: template_name |
| 1583 |
|
| 1584 |
The full name of a template to display the view. Defaults to |
| 1585 |
:file:`registration/password_reset_complete.html`. |
| 1586 |
|
| 1587 |
.. attribute:: extra_context |
| 1588 |
|
| 1589 |
A dictionary of context data that will be added to the default context |
| 1590 |
data passed to the template. |
| 1591 |
|
| 1592 |
Helper functions |
| 1593 |
---------------- |
| 1594 |
|
| 1595 |
.. currentmodule:: django.contrib.auth.views |
| 1596 |
|
| 1597 |
.. function:: redirect_to_login(next, login_url=None, redirect_field_name='next') |
| 1598 |
|
| 1599 |
Redirects to the login page, and then back to another URL after a |
| 1600 |
successful login. |
| 1601 |
|
| 1602 |
**Required arguments:** |
| 1603 |
|
| 1604 |
* ``next``: The URL to redirect to after a successful login. |
| 1605 |
|
| 1606 |
**Optional arguments:** |
| 1607 |
|
| 1608 |
* ``login_url``: The URL of the login page to redirect to. |
| 1609 |
Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied. |
| 1610 |
|
| 1611 |
* ``redirect_field_name``: The name of a ``GET`` field containing the |
| 1612 |
URL to redirect to after login. Overrides ``next`` if the given |
| 1613 |
``GET`` parameter is passed. |
| 1614 |
|
| 1615 |
.. _built-in-auth-forms: |
| 1616 |
|
| 1617 |
Built-in forms |
| 1618 |
-------------- |
| 1619 |
|
| 1620 |
.. module:: django.contrib.auth.forms |
| 1621 |
|
| 1622 |
If you don't want to use the built-in views, but want the convenience of not |
| 1623 |
having to write forms for this functionality, the authentication system |
| 1624 |
provides several built-in forms located in :mod:`django.contrib.auth.forms`: |
| 1625 |
|
| 1626 |
.. note:: |
| 1627 |
The built-in authentication forms make certain assumptions about the user |
| 1628 |
model that they are working with. If you're using a :ref:`custom user model |
| 1629 |
<auth-custom-user>`, it may be necessary to define your own forms for the |
| 1630 |
authentication system. For more information, refer to the documentation |
| 1631 |
about :ref:`using the built-in authentication forms with custom user models |
| 1632 |
<custom-users-and-the-built-in-auth-forms>`. |
| 1633 |
|
| 1634 |
.. class:: AdminPasswordChangeForm |
| 1635 |
|
| 1636 |
A form used in the admin interface to change a user's password, including |
| 1637 |
the ability to set an :meth:`unusable password |
| 1638 |
<django.contrib.auth.models.User.set_unusable_password>`, which blocks the |
| 1639 |
user from logging in with password-based authentication. |
| 1640 |
|
| 1641 |
Takes the ``user`` as the first positional argument. |
| 1642 |
|
| 1643 |
.. versionchanged:: 5.1 |
| 1644 |
|
| 1645 |
Option to disable (or reenable) password-based authentication was |
| 1646 |
added. |
| 1647 |
|
| 1648 |
.. class:: AdminUserCreationForm |
| 1649 |
|
| 1650 |
.. versionadded:: 5.1.1 |
| 1651 |
|
| 1652 |
A form used in the admin interface to create a new user. Inherits from |
| 1653 |
:class:`UserCreationForm`. |
| 1654 |
|
| 1655 |
It includes an additional ``usable_password`` field, enabled by default. If |
| 1656 |
``usable_password`` is enabled, it verifies that ``password1`` and |
| 1657 |
``password2`` are non empty and match, validates the password using |
| 1658 |
:func:`~django.contrib.auth.password_validation.validate_password`, and |
| 1659 |
sets the user's password using |
| 1660 |
:meth:`~django.contrib.auth.models.User.set_password()`. |
| 1661 |
If ``usable_password`` is disabled, no password validation is done, and |
| 1662 |
password-based authentication is disabled for the user by calling |
| 1663 |
:meth:`~django.contrib.auth.models.User.set_unusable_password()`. |
| 1664 |
|
| 1665 |
.. class:: AuthenticationForm |
| 1666 |
|
| 1667 |
A form for logging a user in. |
| 1668 |
|
| 1669 |
Takes ``request`` as its first positional argument, which is stored on the |
| 1670 |
form instance for use by sub-classes. |
| 1671 |
|
| 1672 |
.. method:: confirm_login_allowed(user) |
| 1673 |
|
| 1674 |
By default, ``AuthenticationForm`` rejects users whose ``is_active`` |
| 1675 |
flag is set to ``False``. You may override this behavior with a custom |
| 1676 |
policy to determine which users can log in. Do this with a custom form |
| 1677 |
that subclasses ``AuthenticationForm`` and overrides the |
| 1678 |
``confirm_login_allowed()`` method. This method should raise a |
| 1679 |
:exc:`~django.core.exceptions.ValidationError` if the given user may |
| 1680 |
not log in. |
| 1681 |
|
| 1682 |
For example, to allow all users to log in regardless of "active" |
| 1683 |
status:: |
| 1684 |
|
| 1685 |
from django.contrib.auth.forms import AuthenticationForm |
| 1686 |
|
| 1687 |
|
| 1688 |
class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm): |
| 1689 |
def confirm_login_allowed(self, user): |
| 1690 |
pass |
| 1691 |
|
| 1692 |
(In this case, you'll also need to use an authentication backend that |
| 1693 |
allows inactive users, such as |
| 1694 |
:class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`.) |
| 1695 |
|
| 1696 |
Or to allow only some active users to log in:: |
| 1697 |
|
| 1698 |
class PickyAuthenticationForm(AuthenticationForm): |
| 1699 |
def confirm_login_allowed(self, user): |
| 1700 |
if not user.is_active: |
| 1701 |
raise ValidationError( |
| 1702 |
_("This account is inactive."), |
| 1703 |
code="inactive", |
| 1704 |
) |
| 1705 |
if user.username.startswith("b"): |
| 1706 |
raise ValidationError( |
| 1707 |
_("Sorry, accounts starting with 'b' aren't welcome here."), |
| 1708 |
code="no_b_users", |
| 1709 |
) |
| 1710 |
|
| 1711 |
.. class:: BaseUserCreationForm |
| 1712 |
|
| 1713 |
A :class:`~django.forms.ModelForm` for creating a new user. This is the |
| 1714 |
recommended base class if you need to customize the user creation form. |
| 1715 |
|
| 1716 |
It has three fields: ``username`` (from the user model), ``password1``, |
| 1717 |
and ``password2``. It verifies that ``password1`` and ``password2`` match, |
| 1718 |
validates the password using |
| 1719 |
:func:`~django.contrib.auth.password_validation.validate_password`, and |
| 1720 |
sets the user's password using |
| 1721 |
:meth:`~django.contrib.auth.models.User.set_password()`. |
| 1722 |
|
| 1723 |
.. class:: PasswordChangeForm |
| 1724 |
|
| 1725 |
A form for allowing a user to change their password. |
| 1726 |
|
| 1727 |
.. class:: PasswordResetForm |
| 1728 |
|
| 1729 |
A form for generating and emailing a one-time use link to reset a |
| 1730 |
user's password. |
| 1731 |
|
| 1732 |
.. method:: send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None) |
| 1733 |
|
| 1734 |
Uses the arguments to send an ``EmailMultiAlternatives``. |
| 1735 |
Can be overridden to customize how the email is sent to the user. If |
| 1736 |
you choose to override this method, be mindful of handling potential |
| 1737 |
exceptions raised due to email sending failures. |
| 1738 |
|
| 1739 |
:param subject_template_name: the template for the subject. |
| 1740 |
:param email_template_name: the template for the email body. |
| 1741 |
:param context: context passed to the ``subject_template``, |
| 1742 |
``email_template``, and ``html_email_template`` (if it is not |
| 1743 |
``None``). |
| 1744 |
:param from_email: the sender's email. |
| 1745 |
:param to_email: the email of the requester. |
| 1746 |
:param html_email_template_name: the template for the HTML body; |
| 1747 |
defaults to ``None``, in which case a plain text email is sent. |
| 1748 |
|
| 1749 |
By default, ``save()`` populates the ``context`` with the |
| 1750 |
same variables that |
| 1751 |
:class:`~django.contrib.auth.views.PasswordResetView` passes to its |
| 1752 |
email context. |
| 1753 |
|
| 1754 |
.. class:: SetPasswordForm |
| 1755 |
|
| 1756 |
A form that lets a user change their password without entering the old |
| 1757 |
password. |
| 1758 |
|
| 1759 |
.. class:: UserChangeForm |
| 1760 |
|
| 1761 |
A form used in the admin interface to change a user's information and |
| 1762 |
permissions. |
| 1763 |
|
| 1764 |
.. class:: UserCreationForm |
| 1765 |
|
| 1766 |
Inherits from :class:`BaseUserCreationForm`. To help prevent confusion with |
| 1767 |
similar usernames, the form doesn't allow usernames that differ only in |
| 1768 |
case. |
| 1769 |
|
| 1770 |
.. currentmodule:: django.contrib.auth |
| 1771 |
|
| 1772 |
Authentication data in templates |
| 1773 |
-------------------------------- |
| 1774 |
|
| 1775 |
The currently logged-in user and their permissions are made available in the |
| 1776 |
:doc:`template context </ref/templates/api>` when you use |
| 1777 |
:class:`~django.template.RequestContext`. |
| 1778 |
|
| 1779 |
.. admonition:: Technicality |
| 1780 |
|
| 1781 |
Technically, these variables are only made available in the template |
| 1782 |
context if you use :class:`~django.template.RequestContext` and the |
| 1783 |
``'django.contrib.auth.context_processors.auth'`` context processor is |
| 1784 |
enabled. It is in the default generated settings file. For more, see the |
| 1785 |
:ref:`RequestContext docs <subclassing-context-requestcontext>`. |
| 1786 |
|
| 1787 |
Users |
| 1788 |
~~~~~ |
| 1789 |
|
| 1790 |
When rendering a template :class:`~django.template.RequestContext`, the |
| 1791 |
currently logged-in user, either a :class:`~django.contrib.auth.models.User` |
| 1792 |
instance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is |
| 1793 |
stored in the template variable ``{{ user }}``: |
| 1794 |
|
| 1795 |
.. code-block:: html+django |
| 1796 |
|
| 1797 |
{% if user.is_authenticated %} |
| 1798 |
<p>Welcome, {{ user.username }}. Thanks for logging in.</p> |
| 1799 |
{% else %} |
| 1800 |
<p>Welcome, new user. Please log in.</p> |
| 1801 |
{% endif %} |
| 1802 |
|
| 1803 |
This template context variable is not available if a ``RequestContext`` is not |
| 1804 |
being used. |
| 1805 |
|
| 1806 |
Permissions |
| 1807 |
~~~~~~~~~~~ |
| 1808 |
|
| 1809 |
The currently logged-in user's permissions are stored in the template variable |
| 1810 |
``{{ perms }}``. This is an instance of |
| 1811 |
``django.contrib.auth.context_processors.PermWrapper``, which is a |
| 1812 |
template-friendly proxy of permissions. |
| 1813 |
|
| 1814 |
Evaluating a single-attribute lookup of ``{{ perms }}`` as a boolean is a proxy |
| 1815 |
to :meth:`User.has_module_perms() |
| 1816 |
<django.contrib.auth.models.User.has_module_perms>`. For example, to check if |
| 1817 |
the logged-in user has any permissions in the ``foo`` app: |
| 1818 |
|
| 1819 |
.. code-block:: html+django |
| 1820 |
|
| 1821 |
{% if perms.foo %} |
| 1822 |
|
| 1823 |
Evaluating a two-level-attribute lookup as a boolean is a proxy to |
| 1824 |
:meth:`User.has_perm() <django.contrib.auth.models.User.has_perm>`. For example, |
| 1825 |
to check if the logged-in user has the permission ``foo.add_vote``: |
| 1826 |
|
| 1827 |
.. code-block:: html+django |
| 1828 |
|
| 1829 |
{% if perms.foo.add_vote %} |
| 1830 |
|
| 1831 |
Here's a more complete example of checking permissions in a template: |
| 1832 |
|
| 1833 |
.. code-block:: html+django |
| 1834 |
|
| 1835 |
{% if perms.foo %} |
| 1836 |
<p>You have permission to do something in the foo app.</p> |
| 1837 |
{% if perms.foo.add_vote %} |
| 1838 |
<p>You can vote!</p> |
| 1839 |
{% endif %} |
| 1840 |
{% if perms.foo.add_driving %} |
| 1841 |
<p>You can drive!</p> |
| 1842 |
{% endif %} |
| 1843 |
{% else %} |
| 1844 |
<p>You don't have permission to do anything in the foo app.</p> |
| 1845 |
{% endif %} |
| 1846 |
|
| 1847 |
It is possible to also look permissions up by ``{% if in %}`` statements. |
| 1848 |
For example: |
| 1849 |
|
| 1850 |
.. code-block:: html+django |
| 1851 |
|
| 1852 |
{% if 'foo' in perms %} |
| 1853 |
{% if 'foo.add_vote' in perms %} |
| 1854 |
<p>In lookup works, too.</p> |
| 1855 |
{% endif %} |
| 1856 |
{% endif %} |
| 1857 |
|
| 1858 |
.. _auth-admin: |
| 1859 |
|
| 1860 |
Managing users in the admin |
| 1861 |
=========================== |
| 1862 |
|
| 1863 |
When you have both ``django.contrib.admin`` and ``django.contrib.auth`` |
| 1864 |
installed, the admin provides a convenient way to view and manage users, |
| 1865 |
groups, and permissions. Users can be created and deleted like any Django |
| 1866 |
model. Groups can be created, and permissions can be assigned to users or |
| 1867 |
groups. A log of user edits to models made within the admin is also stored and |
| 1868 |
displayed. |
| 1869 |
|
| 1870 |
Creating users |
| 1871 |
-------------- |
| 1872 |
|
| 1873 |
You should see a link to "Users" in the "Auth" |
| 1874 |
section of the main admin index page. The "Add user" admin page is different |
| 1875 |
than standard admin pages in that it requires you to choose a username and |
| 1876 |
password before allowing you to edit the rest of the user's fields. |
| 1877 |
Alternatively, on this page, you can choose a username and disable |
| 1878 |
password-based authentication for the user. |
| 1879 |
|
| 1880 |
Also note: if you want a user account to be able to create users using the |
| 1881 |
Django admin site, you'll need to give them permission to add users *and* |
| 1882 |
change users (i.e., the "Add user" and "Change user" permissions). If an |
| 1883 |
account has permission to add users but not to change them, that account won't |
| 1884 |
be able to add users. Why? Because if you have permission to add users, you |
| 1885 |
have the power to create superusers, which can then, in turn, change other |
| 1886 |
users. So Django requires add *and* change permissions as a slight security |
| 1887 |
measure. |
| 1888 |
|
| 1889 |
Be thoughtful about how you allow users to manage permissions. If you give a |
| 1890 |
non-superuser the ability to edit users, this is ultimately the same as giving |
| 1891 |
them superuser status because they will be able to elevate permissions of |
| 1892 |
users including themselves! |
| 1893 |
|
| 1894 |
Changing passwords |
| 1895 |
------------------ |
| 1896 |
|
| 1897 |
User passwords are not displayed in the admin (nor stored in the database), but |
| 1898 |
the :doc:`password storage details </topics/auth/passwords>` are displayed. |
| 1899 |
Included in the display of this information is a link to |
| 1900 |
a password change form that allows admins to change or unset user passwords. |