Skip to content

Commit b65b065

Browse files
Add DjangoModelPermissionsOrAnonReadOnly
1 parent 8dff8d2 commit b65b065

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

docs/api-guide/permissions.md

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,16 +96,15 @@ This permission class ties into Django's standard `django.contrib.auth` [model p
9696
* `POST` requests require the user to have the `add` permission on the model.
9797
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
9898
* `DELETE` requests require the user to have the `delete` permission on the model.
99-
100-
If you want to use `DjangoModelPermissions` but also allow unauthenticated users to have read permission, override the class and set the `authenticated_users_only` property to `False`. For example:
101-
102-
class HasModelPermissionsOrReadOnly(DjangoModelPermissions):
103-
authenticated_users_only = False
10499

105100
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
106101

107102
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
108103

104+
## DjangoModelPermissionsOrAnonReadOnly
105+
106+
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
107+
109108
## TokenHasReadWriteScope
110109

111110
This permission class is intended for use with either of the `OAuthAuthentication` and `OAuth2Authentication` classes, and ties into the scoping that their backends provide.

rest_framework/permissions.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,8 @@ class DjangoModelPermissions(BasePermission):
8989
It ensures that the user is authenticated, and has the appropriate
9090
`add`/`change`/`delete` permissions on the model.
9191
92-
This permission will only be applied against view classes that
93-
provide a `.model` attribute, such as the generic class-based views.
92+
This permission can only be applied against view classes that
93+
provide a `.model` or `.queryset` attribute.
9494
"""
9595

9696
# Map methods into required permission codes.
@@ -138,6 +138,14 @@ def has_permission(self, request, view):
138138
return False
139139

140140

141+
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
142+
"""
143+
Similar to DjangoModelPermissions, except that anonymous users are
144+
allowed read-only access.
145+
"""
146+
authenticated_users_only = False
147+
148+
141149
class TokenHasReadWriteScope(BasePermission):
142150
"""
143151
The request is authenticated as a user and the token used has the right scope

0 commit comments

Comments
 (0)