Skip to content

Improve viewset action docs #9638

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
k0t3n opened this issue Jan 29, 2025 · 3 comments
Open

Improve viewset action docs #9638

k0t3n opened this issue Jan 29, 2025 · 3 comments

Comments

@k0t3n
Copy link

k0t3n commented Jan 29, 2025

Hi,
I encountered a problem when overriding viewset-level attributes doesn't work for actions if a route is configured as .as_view().

Example:

# views.py
class TestView(viewsets.ModelViewSet):
    @action(methods=['get'], detail=False, url_name='test_action', permission_classes=[IsAuthenticated,])
    def test_action(self, request):
        return Response()

# urls.py
urlpatterns = [
    path('test_urlpattern/', TestViewSet.as_view({'get': 'test_action'},)),
]

# tests.py
@pytest.mark.django_db
def test_case(client):
    url = reverse('test_urlpattern')
    response = client.get(url)
    assert response.status_code == 200  # expected 401!

You can override it using initkwargs only

# urls.py
urlpatterns = [
    # permission will be added
    path('test_urlpattern/', TestViewSet.as_view({'get': 'test_action'}, permission_classes=[IsAuthenticated, ])),
]

According to the docs, it's not clear this feature works for Router configuration only. No exceptions, warnings, or even related github issues were found regarding this.

Image
Copy link

stale bot commented Apr 27, 2025

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Apr 27, 2025
@auvipy
Copy link
Member

auvipy commented Apr 28, 2025

isn't .as_view only work for class based views only? do we need this in viewsets?

@stale stale bot removed the stale label Apr 28, 2025
@k0t3n
Copy link
Author

k0t3n commented Apr 28, 2025

isn't .as_view only work for class based views only? do we need this in viewsets?

If your question is whether the drf needs .as_view() in view sets, I believe yes, at least because lots of users' code may rely on it. My suggestion is to add some sort of validation or warning on passing arguments to .as_view(), since if you try to reroute GET requests to a specific function (action) the requests would just be passed to the default get() handler no matter what you configured before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants