Djoser - Override registration

Viewed 1010

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?

1 Answers

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.

Related