4

I'm confused as to how to modify the registration endpoint for Djoser. All I would like to do is add scoped throttling to the endpoint, but I can't understand how to override it. This page on the docs talks about it: https://djoser.readthedocs.io/en/2.1.0/adjustment.html But it seems outdated? How would it be done today with the UserViewSet & make sure the url works as intended?

Thorvald
  • 546
  • 6
  • 18

1 Answers1

5

What you can do is to subclass djoser UserViewSet and add your extra code. Something like this should work

# your_views.py

from djoser.views import UserViewSet as DjoserUserViewSet


class UserViewSet(DjoserUserViewSet):

    def get_throttles(self):
        if self.action == "create":
            self.throttle_classes = [YourThrottleClass]
        return super().get_throttles()

And then in your urls.py you should NOT include djoser.urls in your urlpatterns

Instead of this (taken from their docs, you might have other url):

urlpatterns = [
    (...),
    url(r'^auth/', include('djoser.urls')),
]

Do this in your urlpatterns (you may already have a router defined):

# I have use endpoint "auth/users" to keep it similar to the above, but it can be just simple "users"

router = DefaultRouter()
router.register("auth/users", your_views.UserViewSet)  

urlpatterns = [
    (...),
    url(r'^', include(router.urls)),
]

Behind the scene djoser.urls is registering users endpoint but with their internal UserViewSet so in this way you can use your own custom class.

Gabriel Muj
  • 3,682
  • 1
  • 19
  • 28
  • This worked, I had to remove the quotes around router.urls though, e.g url(r'^', include(router.urls)). Also instead of adding a throttle class I was also able to add throttle_scope instead, using self.throttle_scope = "mycustomscope" instead of self.throttle_classses. Also using djoser_views.UserViewSet didn't work, I had to import the UserViewSet. Maybe you can edit your answer :) Thank you! The way the router works when overriding & needing to call the super was the points I must have failed at previously. – Thorvald Feb 04 '21 at 12:12
  • I have edited the answer to fix the problems described. – Gabriel Muj Feb 04 '21 at 12:33