re: Managing RESTful URLs in Django Rest Framework VIEW POST


Thanks! Nice post and nice idea. Unfortunately the issues are starting when you're starting to add some security or permissions.

For example you need to make GET method public and protect others. If you add permissions to the classes you've mapped, they simply would skip the permissions check from your classes as and would apply the permissions from ProductManageView only.

Still the idea of yours is nice!

P.S. Correct me if I'm mistaken about permissions :)


Fortunately, you are mistaken. You can very simply add a permission class to the view you want to protect and it works how you'd expect it.
Say we want only authorized users to delete our products. We'd simply add the IsAuthorized permission class to the delete view

from rest_framework.permissions import IsAuthenticated

class ProductDestroyView(DestroyAPIView):
    permission_classes = (IsAuthenticated, )
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

Our new test

def test_destroy_view_requires_authentication(self):
        product = Product.objects.create(name='Apple Watch', price=500, stock=3)
        response = self.client.delete(f'/products/{product.id}')
        self.assertEqual(response.status_code, 403)
        self.assertEqual(Product.objects.count(), 1)  # assert not deleted


Stanislavs-iMac:restful_drf stanislavkozlovski$ python3.6 manage.py test restful_example.tests.ProductTests.test_destroy_view_requires_authentication
Creating test database for alias 'default'...
Ran 1 test in 0.014s

Destroying test database for alias 'default'...

I'm so glad I've asked about it! :) Thank you. Please, consider to add the information about permissions to the main article, it's very useful. Thank you!

code of conduct - report abuse