[Note] About a mixin to close a page for non-staff

A small piece of code, very simple.

Based on django.contrib.auth.mixins.LoginRequiredMixin, change that code a bit:

class StaffMixin(AccessMixin):
"""Verify that the current user is staff."""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)

And in order to use it, inherit it in a GenericView:

class PostView(DetailView, StaffMixin):
   # ... get on with your day

I am all for using GenericView‘s for everything, especially for mixins.

For a FBV (function def) you can do a decorator:

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_staff)
def your_fbv(request):
   # body

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.