diff --git a/api-guide/authentication/index.html b/api-guide/authentication/index.html index 30f104718..55d07bc6b 100644 --- a/api-guide/authentication/index.html +++ b/api-guide/authentication/index.html @@ -429,6 +429,10 @@ Unauthorized and Forbidden responses +
  • + Django 5.1+ LoginRequiredMiddleware +
  • +
  • Apache mod_wsgi specific configuration
  • @@ -605,6 +609,9 @@ def example_view(request, format=None):

    HTTP 401 responses must always include a WWW-Authenticate header, that instructs the client how to authenticate. HTTP 403 responses do not include the WWW-Authenticate header.

    The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. The first authentication class set on the view is used when determining the type of response.

    Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a 403 Permission Denied response will always be used, regardless of the authentication scheme.

    +

    Django 5.1+ LoginRequiredMiddleware

    +

    If you're running Django 5.1+ and use the LoginRequiredMiddleware, please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code.

    +

    REST framework offers an equivalent mechanism for DRF views via the global settings, DEFAULT_AUTHENTICATION_CLASSES and DEFAULT_PERMISSION_CLASSES. They should be changed accordingly if you need to enforce that API requests are logged in.

    Apache mod_wsgi specific configuration

    Note that if deploying to Apache using mod_wsgi, the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.

    If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the WSGIPassAuthorization directive in the appropriate context and setting it to 'On'.

    diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html index 1f0f70a0c..ffc58e61e 100644 --- a/api-guide/fields/index.html +++ b/api-guide/fields/index.html @@ -832,8 +832,8 @@ explicitly declare the BooleanField on the serializer class, or use
  • max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places.
  • decimal_places The number of decimal places to store with the number.
  • coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True.
  • -
  • max_value Validate that the number provided is no greater than this value.
  • -
  • min_value Validate that the number provided is no less than this value.
  • +
  • max_value Validate that the number provided is no greater than this value. Should be an integer or Decimal object.
  • +
  • min_value Validate that the number provided is no less than this value. Should be an integer or Decimal object.
  • localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True. Defaults to False. Note that data formatting is enabled if you have set USE_L10N=True in your settings file.
  • rounding Sets the rounding mode used when quantizing to the configured precision. Valid values are decimal module rounding modes. Defaults to None.
  • normalize_output Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to False.
  • diff --git a/api-guide/renderers/index.html b/api-guide/renderers/index.html index 159729fb9..615b49fa2 100644 --- a/api-guide/renderers/index.html +++ b/api-guide/renderers/index.html @@ -942,7 +942,7 @@ class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet):

    Pandas (CSV, Excel, PNG)

    Django REST Pandas provides a serializer and renderers that support additional data processing and output via the Pandas DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both .xls and .xlsx), and a number of other formats. It is maintained by S. Andrew Sheppard as part of the wq Project.

    LaTeX

    -

    Rest Framework Latex provides a renderer that outputs PDFs using Laulatex. It is maintained by Pebble (S/F Software).

    +

    Rest Framework Latex provides a renderer that outputs PDFs using Lualatex. It is maintained by Pebble (S/F Software).

    diff --git a/api-guide/routers/index.html b/api-guide/routers/index.html index e05f9ddf1..2a31916e2 100644 --- a/api-guide/routers/index.html +++ b/api-guide/routers/index.html @@ -606,6 +606,20 @@ class UserViewSet(ModelViewSet):
  • URL path: ^users/{pk}/change-password/$
  • URL name: 'user-change_password'
  • +

    Using Django path() with routers

    +

    By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the use_regex_path argument to False when instantiating the router, in this case path converters are used. For example:

    +
    router = SimpleRouter(use_regex_path=False)
    +
    +

    The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the lookup_value_regex attribute on the viewset or lookup_value_converter if using path converters. For example, you can limit the lookup to valid UUIDs:

    +
    class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    +    lookup_field = 'my_model_id'
    +    lookup_value_regex = '[0-9a-f]{32}'
    +
    +class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    +    lookup_field = 'my_model_uuid'
    +    lookup_value_converter = 'uuid'
    +
    +

    Note that path converters will be used on all URLs registered in the router, including viewset actions.

    API Guide

    SimpleRouter

    This router includes routes for the standard set of list, create, retrieve, update, partial_update and destroy actions. The viewset can also mark additional methods to be routed, using the @action decorator.

    @@ -621,24 +635,11 @@ class UserViewSet(ModelViewSet): {prefix}/{lookup}/{url_path}/GET, or as specified by `methods` argument`@action(detail=True)` decorated method{basename}-{url_name} -

    By default the URLs created by SimpleRouter are appended with a trailing slash. +

    By default, the URLs created by SimpleRouter are appended with a trailing slash. This behavior can be modified by setting the trailing_slash argument to False when instantiating the router. For example:

    router = SimpleRouter(trailing_slash=False)
     

    Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.

    -

    By default the URLs created by SimpleRouter use regular expressions. This behavior can be modified by setting the use_regex_path argument to False when instantiating the router, in this case path converters are used. For example:

    -
    router = SimpleRouter(use_regex_path=False)
    -
    -

    Note: use_regex_path=False only works with Django 2.x or above, since this feature was introduced in 2.0.0. See release note

    -

    The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the lookup_value_regex attribute on the viewset or lookup_value_converter if using path converters. For example, you can limit the lookup to valid UUIDs:

    -
    class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    -    lookup_field = 'my_model_id'
    -    lookup_value_regex = '[0-9a-f]{32}'
    -
    -class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    -    lookup_field = 'my_model_uuid'
    -    lookup_value_converter = 'uuid'
    -

    DefaultRouter

    This router is similar to SimpleRouter as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional .json style format suffixes.

    diff --git a/api-guide/serializers/index.html b/api-guide/serializers/index.html index bbeba7a13..55c1de42b 100644 --- a/api-guide/serializers/index.html +++ b/api-guide/serializers/index.html @@ -845,7 +845,7 @@ class GameRecord(serializers.Serializer):

    Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner Meta class, like so:

    class EventSerializer(serializers.Serializer):
         name = serializers.CharField()
    -    room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
    +    room_number = serializers.ChoiceField(choices=[101, 102, 103, 201])
         date = serializers.DateField()
     
         class Meta:
    diff --git a/api-guide/settings/index.html b/api-guide/settings/index.html
    index 70dca17f6..472840bb8 100644
    --- a/api-guide/settings/index.html
    +++ b/api-guide/settings/index.html
    @@ -657,27 +657,27 @@ internally in the codebase.

    The following settings are used to control how date and time representations may be parsed and rendered.

    DATETIME_FORMAT

    A format string that should be used by default for rendering the output of DateTimeField serializer fields. If None, then DateTimeField serializer fields will return Python datetime objects, and the datetime encoding will be determined by the renderer.

    -

    May be any of None, 'iso-8601' or a Python strftime format string.

    +

    May be any of None, 'iso-8601' or a Python strftime format string.

    Default: 'iso-8601'

    DATETIME_INPUT_FORMATS

    A list of format strings that should be used by default for parsing inputs to DateTimeField serializer fields.

    -

    May be a list including the string 'iso-8601' or Python strftime format strings.

    +

    May be a list including the string 'iso-8601' or Python strftime format strings.

    Default: ['iso-8601']

    DATE_FORMAT

    A format string that should be used by default for rendering the output of DateField serializer fields. If None, then DateField serializer fields will return Python date objects, and the date encoding will be determined by the renderer.

    -

    May be any of None, 'iso-8601' or a Python strftime format string.

    +

    May be any of None, 'iso-8601' or a Python strftime format string.

    Default: 'iso-8601'

    DATE_INPUT_FORMATS

    A list of format strings that should be used by default for parsing inputs to DateField serializer fields.

    -

    May be a list including the string 'iso-8601' or Python strftime format strings.

    +

    May be a list including the string 'iso-8601' or Python strftime format strings.

    Default: ['iso-8601']

    TIME_FORMAT

    A format string that should be used by default for rendering the output of TimeField serializer fields. If None, then TimeField serializer fields will return Python time objects, and the time encoding will be determined by the renderer.

    -

    May be any of None, 'iso-8601' or a Python strftime format string.

    +

    May be any of None, 'iso-8601' or a Python strftime format string.

    Default: 'iso-8601'

    TIME_INPUT_FORMATS

    A list of format strings that should be used by default for parsing inputs to TimeField serializer fields.

    -

    May be a list including the string 'iso-8601' or Python strftime format strings.

    +

    May be a list including the string 'iso-8601' or Python strftime format strings.

    Default: ['iso-8601']


    Encodings

    diff --git a/api-guide/testing/index.html b/api-guide/testing/index.html index 9c1ff0d0e..f234ee81e 100644 --- a/api-guide/testing/index.html +++ b/api-guide/testing/index.html @@ -569,9 +569,12 @@ # Using the standard RequestFactory API to create a form POST request factory = APIRequestFactory() request = factory.post('/notes/', {'title': 'new idea'}) + +# Using the standard RequestFactory API to encode JSON data +request = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json')

    Using the format argument

    -

    Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a content type other than multipart form data. For example:

    +

    Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured content_type. For example:

    # Create a JSON POST request
     factory = APIRequestFactory()
     request = factory.post('/notes/', {'title': 'new idea'}, format='json')
    @@ -580,7 +583,7 @@ request = factory.post('/notes/', {'title': 'new idea'}, format='json')
     

    To support a wider set of request formats, or change the default format, see the configuration section.

    Explicitly encoding the request body

    If you need to explicitly encode the request body, you can do so by setting the content_type flag. For example:

    -
    request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json')
    +
    request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml')
     

    PUT and PATCH with form data

    One difference worth noting between Django's RequestFactory and REST framework's APIRequestFactory is that multipart form data will be encoded for methods other than just .post().

    diff --git a/api-guide/validators/index.html b/api-guide/validators/index.html index dd8747274..db5172488 100644 --- a/api-guide/validators/index.html +++ b/api-guide/validators/index.html @@ -543,7 +543,7 @@ CustomerReportSerializer(): id = IntegerField(label='ID', read_only=True) time_raised = DateTimeField(read_only=True) - reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>]) + reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())]) description = CharField(style={'type': 'textarea'})

    The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.

    diff --git a/community/jobs/index.html b/community/jobs/index.html index d262c320a..47655a0b6 100644 --- a/community/jobs/index.html +++ b/community/jobs/index.html @@ -442,6 +442,7 @@

    Videos

    @@ -502,6 +503,7 @@
  • Django REST API - So Easy You Can Learn It in 25 Minutes
  • Tom Christie about Django Rest Framework at Django: Under The Hood
  • Django REST Framework: Schemas, Hypermedia & Client Libraries
  • +
  • Finally Understand Authentication in Django REST Framework
  • Tutorials