Search code examples
djangospring-bootdjango-rest-frameworkdjango-viewsdjango-permissions

Django Authorization Checking in URL having wild card pattern


I am trying to implement permission checking mechanism in URLs for a request using wildcard techniques, rather than implement permission checking on each views.

Currently What I have is.

urlpatterns = [
    path('admin/', include('admin_urls.py')),
    ...
]

and my admin_urls.py is as follows

urlpatterns = [
    path('', ViewSpaceIndex.as_view(), name="admin_index"),
     path('', EmployeeView.as_view(), name="employee"),
    ...
]

and views are as follows

@method_decorator(admin_required, name='dispatch')
 class EmployeeView(TemplateView):
     template_name = 'secret.html'



@method_decorator(admin_required, name='dispatch')
 class EmployeeView(TemplateView):
     template_name = 'secret.html'

What I want to achieve is without using the repeated @method_decorator(admin_required, name='dispatch') decorator in every view I want to apply the permission to a wild card URLs '/admin/**' with admin_required permission like in Spring boot as follows.

  http.authorizeRequests()
           
            .antMatchers("/admin/**").has_permission("is_admin")
            

Solution

  • You can do this in your project root url like this:

    from .my_custom_decorators import admin_required
    urlpatterns = [
        path('admin/', admin_required(include('admin_urls.py'))),
        ...
    ]
    

    I don't know this will work or not but you can try.