Home > OS >  How would I ensure that only authorised users are able to access this class based view
How would I ensure that only authorised users are able to access this class based view

Time:11-13

I have a risk entry view that only project managers are able to access and no other user group how would I ensure that only this user group is able to access this view?

Risk page class-based view

@method_decorator(decorators, name='dispatch')
class Risk_entry_page(View):

    template_name = 'risk/riskEntry.html'

    def get(self, request, *args, **kwargds):
        return render(request, self.template_name)

Risk Urls

urlpatterns = [
    path('', views.Solution_area_home_page.as_view(), name='risks-home-page'),
    path('risk/', views.Risk_entry_page.as_view(), name='risk-entry-page'),
    path('assumption/', views.Assumption_entry_page.as_view(), name='assumption-entry-page'),
    path('issue/', views.Issue_entry_page.as_view(), name='issue-entry-page'),
    path('dependency/', views.Dependency_entry_page.as_view(), name='dependency-entry-page'),
    path('logout/', views.Logout.as_view(), name='logout-view'),
]

CodePudding user response:

If you want to give access to Authorized user only then you can introduce Permission in your project, so that user with certain permission can be accesible to your Risk_entry_page class https://django-permission.readthedocs.io/en/latest/

If You want only login user can access, you Risk_entry_page class then use Login Required mixin.

from django.contrib.auth.mixins import LoginRequiredMixin

@method_decorator(decorators, name='dispatch')
class Risk_entry_page(LoginRequiredMixin, View):

    template_name = 'risk/riskEntry.html'

    def get(self, request, *args, **kwargds):
        return render(request, self.template_name)

CodePudding user response:

You can limit views to a class-based view to authenticated users with the LoginRequiredMixin mixin [Django-doc]. You probably however want to limit the view to users with a given (set of) permission(s) with the PermissionRequiredMixin mixin [Django-doc]:

from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import TemplateView


class MyView(PermissionRequiredMixin, TemplateView):
    permission_required = 'some_app.some_permssion'
    template_name = 'risk/riskEntry.html'
  • Related