DEV Community

Discussion on: Managing RESTful URLs in Django Rest Framework

Collapse
 
enether profile image
Stanislav Kozlovski

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

Passes!

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

OK
Destroying test database for alias 'default'...
Collapse
 
khorolets profile image
Bohdan Khorolets

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!

Thread Thread
 
enether profile image
Stanislav Kozlovski

Done, thanks for the idea!