You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<p>Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.</p>
563
563
<p>The <code>request.user</code> property will typically be set to an instance of the <code>contrib.auth</code> package's <code>User</code> class.</p>
564
564
<p>The <code>request.auth</code> property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.</p>
565
-
<hr/>
566
-
<p><strong>Note:</strong> Don't forget that <strong>authentication by itself won't allow or disallow an incoming request</strong>, it simply identifies the credentials that the request was made with.</p>
565
+
<divclass="admonition note">
566
+
<pclass="admonition-title">Note</p>
567
+
<p>Don't forget that <strong>authentication by itself won't allow or disallow an incoming request</strong>, it simply identifies the credentials that the request was made with.</p>
567
568
<p>For information on how to set up the permission policies for your API please see the <ahref="../permissions/">permissions documentation</a>.</p>
568
-
<hr/>
569
+
</div>
569
570
<h2id="how-authentication-is-determined"><aclass="toclink" href="#how-authentication-is-determined">How authentication is determined</a></h2>
570
571
<p>The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set <code>request.user</code> and <code>request.auth</code> using the return value of the first class that successfully authenticates.</p>
571
572
<p>If no class authenticates, <code>request.user</code> will be set to an instance of <code>django.contrib.auth.models.AnonymousUser</code>, and <code>request.auth</code> will be set to <code>None</code>.</p>
<p>Unauthenticated responses that are denied permission will result in an <code>HTTP 401 Unauthorized</code> response with an appropriate WWW-Authenticate header. For example:</p>
639
640
<pre><code>WWW-Authenticate: Basic realm="api"
640
641
</code></pre>
641
-
<p><strong>Note:</strong> If you use <code>BasicAuthentication</code> in production you must ensure that your API is only available over <code>https</code>. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.</p>
642
+
<divclass="admonition note">
643
+
<pclass="admonition-title">Note</p>
644
+
<p>If you use <code>BasicAuthentication</code> in production you must ensure that your API is only available over <code>https</code>. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.</p>
<p><strong>Note:</strong> The token authentication provided by Django REST framework is a fairly simple implementation.</p>
647
+
<divclass="admonition note">
648
+
<pclass="admonition-title">Note</p>
649
+
<p>The token authentication provided by Django REST framework is a fairly simple implementation.</p>
645
650
<p>For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the <ahref="https://github.com/James1345/django-rest-knox">Django REST Knox</a> third party package.</p>
646
-
<hr/>
651
+
</div>
647
652
<p>This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.</p>
648
653
<p>To use the <code>TokenAuthentication</code> scheme you'll need to <ahref="#setting-the-authentication-scheme">configure the authentication classes</a> to include <code>TokenAuthentication</code>, and additionally include <code>rest_framework.authtoken</code> in your <code>INSTALLED_APPS</code> setting:</p>
<p>The <code>curl</code> command line tool may be useful for testing token authenticated APIs. For example:</p>
675
680
<pre><code>curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
676
681
</code></pre>
677
-
<hr/>
678
-
<p><strong>Note:</strong> If you use <code>TokenAuthentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
679
-
<hr/>
682
+
<divclass="admonition note">
683
+
<pclass="admonition-title">Note</p>
684
+
<p>If you use <code>TokenAuthentication</code> in production you must ensure that your API is only available over <code>https</code>.</p>
<p>You <em>may</em> also override the <code>.authenticate_header(self, request)</code> method. If implemented, it should return a string that will be used as the value of the <code>WWW-Authenticate</code> header in a <code>HTTP 401 Unauthorized</code> response.</p>
797
803
<p>If the <code>.authenticate_header()</code> method is not overridden, the authentication scheme will return <code>HTTP 403 Forbidden</code> responses when an unauthenticated request is denied access.</p>
798
-
<hr/>
799
-
<p><strong>Note:</strong> When your custom authenticator is invoked by the request object's <code>.user</code> or <code>.auth</code> properties, you may see an <code>AttributeError</code> re-raised as a <code>WrappedAttributeError</code>. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the <code>AttributeError</code> originates from your custom authenticator and will instead assume that the request object does not have a <code>.user</code> or <code>.auth</code> property. These errors should be fixed or otherwise handled by your authenticator.</p>
800
-
<hr/>
804
+
<divclass="admonition note">
805
+
<pclass="admonition-title">Note</p>
806
+
<p>When your custom authenticator is invoked by the request object's <code>.user</code> or <code>.auth</code> properties, you may see an <code>AttributeError</code> re-raised as a <code>WrappedAttributeError</code>. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the <code>AttributeError</code> originates from your custom authenticator and will instead assume that the request object does not have a <code>.user</code> or <code>.auth</code> property. These errors should be fixed or otherwise handled by your authenticator.</p>
<p><strong>NOTE:</strong> The <ahref="https://docs.djangoproject.com/en/stable/topics/cache/#the-per-view-cache"><code>cache_page</code></a> decorator only caches the
516
-
<code>GET</code> and <code>HEAD</code> responses with status 200.</p>
515
+
<divclass="admonition note">
516
+
<pclass="admonition-title">Note</p>
517
+
<p>The <ahref="https://docs.djangoproject.com/en/stable/topics/cache/#the-per-view-cache"><code>cache_page</code></a> decorator only caches the <code>GET</code> and <code>HEAD</code> responses with status 200.</p>
<p>If the requested view was only configured with renderers for <code>YAML</code> and <code>HTML</code>, then REST framework would select whichever renderer was listed first in the <code>renderer_classes</code> list or <code>DEFAULT_RENDERER_CLASSES</code> setting.</p>
481
481
<p>For more information on the <code>HTTP Accept</code> header, see <ahref="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">RFC 2616</a></p>
482
-
<hr/>
483
-
<p><strong>Note</strong>: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.</p>
482
+
<divclass="admonition note">
483
+
<pclass="admonition-title">Note</p>
484
+
<p>"q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.</p>
484
485
<p>This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.</p>
<p>It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override <code>BaseContentNegotiation</code>.</p>
488
489
<p>REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the <code>.select_parser(request, parsers)</code> and <code>.select_renderer(request, renderers, format_suffix)</code> methods.</p>
<p>Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.</p>
655
-
<hr/>
656
-
<p><strong>Note:</strong> The serializer fields are declared in <code>fields.py</code>, but by convention you should import them using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.<FieldName></code>.</p>
657
-
<hr/>
655
+
<divclass="admonition note">
656
+
<pclass="admonition-title">Note</p>
657
+
<p>The serializer fields are declared in <code>fields.py</code>, but by convention you should import them using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.<FieldName></code>.</p>
<p>Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:</p>
<p>The <code>HiddenField</code> class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.</p>
1032
1033
<p>For further examples on <code>HiddenField</code> see the <ahref="../validators/">validators</a> documentation.</p>
1033
-
<hr/>
1034
-
<p><strong>Note:</strong><code>HiddenField()</code> does not appear in <code>partial=True</code> serializer (when making <code>PATCH</code> request).</p>
1035
-
<hr/>
1034
+
<divclass="admonition note">
1035
+
<pclass="admonition-title">Note</p>
1036
+
<p><code>HiddenField()</code> does not appear in <code>partial=True</code> serializer (when making <code>PATCH</code> request).</p>
<p>A generic field that can be tied to any arbitrary model field. The <code>ModelField</code> class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p>
1038
1040
<p>This field is used by <code>ModelSerializer</code> to correspond to custom model field classes.</p>
<p><strong>Note:</strong> If the <code>serializer_class</code> used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using <code>select_related</code> and <code>prefetch_related</code>. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in <ahref="https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related">django documentation</a>.</p>
628
-
<hr/>
626
+
<divclass="admonition tip">
627
+
<pclass="admonition-title">Tip</p>
628
+
<p>If the <code>serializer_class</code> used in the generic view spans ORM relations, leading to an N+1 problem, you could optimize your queryset in this method using <code>select_related</code> and <code>prefetch_related</code>. To get more information about N+1 problem and use cases of the mentioned methods refer to related section in <ahref="https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related">django documentation</a>.</p>
<p>When listing objects (e.g. using <code>ListAPIView</code> or <code>ModelViewSet</code>), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item.</p>
631
632
<p>To prevent this, optimize the queryset in <code>get_queryset()</code> or by setting the <code>queryset</code> class attribute using <ahref="https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-related"><code>select_related()</code></a> and <ahref="https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related"><code>prefetch_related()</code></a>, depending on the type of relationship.</p>
<p>REST framework includes a number of built-in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.</p>
523
523
<h2id="how-the-parser-is-determined"><aclass="toclink" href="#how-the-parser-is-determined">How the parser is determined</a></h2>
524
524
<p>The set of valid parsers for a view is always defined as a list of classes. When <code>request.data</code> is accessed, REST framework will examine the <code>Content-Type</code> header on the incoming request, and determine which parser to use to parse the request content.</p>
525
-
<hr/>
526
-
<p><strong>Note</strong>: When developing client applications always remember to make sure you're setting the <code>Content-Type</code> header when sending data in an HTTP request.</p>
527
-
<p>If you don't set the content type, most clients will default to using <code>'application/x-www-form-urlencoded'</code>, which may not be what you wanted.</p>
525
+
<divclass="admonition note">
526
+
<pclass="admonition-title">Note</p>
527
+
<p>When developing client applications always remember to make sure you're setting the <code>Content-Type</code> header when sending data in an HTTP request.</p>
528
+
<p>If you don't set the content type, most clients will default to using <code>'application/x-www-form-urlencoded'</code>, which may not be what you want.</p>
528
529
<p>As an example, if you are sending <code>json</code> encoded data using jQuery with the <ahref="https://api.jquery.com/jQuery.ajax/">.ajax() method</a>, you should make sure to include the <code>contentType: 'application/json'</code> setting.</p>
529
-
<hr/>
530
+
</div>
530
531
<h2id="setting-the-parsers"><aclass="toclink" href="#setting-the-parsers">Setting the parsers</a></h2>
531
532
<p>The default set of parsers may be set globally, using the <code>DEFAULT_PARSER_CLASSES</code> setting. For example, the following settings would allow only requests with <code>JSON</code> content, instead of the default of JSON or form data.</p>
0 commit comments