Here are additional resources about Python lambda functions and Django user_passes_test:
Restricting Views to Admin and Staff
00:00 Restricting Views to Admin and Staff. You’ve now written a Django view with authorization. But authorization could be more complicated than simply checking whether a user is authenticated. Django has three roles out of the box: user, staff, and superuser.
You can also authorize based on the three roles. To experiment with this feature, you’re going to need a few more user accounts. Go to the admin area at the URL seen onscreen, click the Add button next to the Users object link, and use this screen to add a new user with a username
Once you create the user, you’ll automatically be sent to the edit user page, where you can specify further details. But the defaults are good enough for
bob. Scroll to the bottom and click Save and add another. Once again, you’ll be prompted to create a user. This time, create
You should be able to log into the admin area using either the
sylvia accounts. As staff, you can get into the admin area, but you won’t be able to see anything by default. You don’t have permission.
If you haven’t seen a
lambda before, then think of it as a miniature, anonymous function. After the
lambda keyword is the named parameter for the
lambda, which in this case is
user. To the right of the colon (
:) is the test.
This test looks at the
HttpRequest.user.is_staff attribute. If it’s
True, then the test passes. For more information about
lambda functions and how they work, check out the Real Python How to Use Python Lambda Functions course.
You now see that visiting
/staff_place/ signed in with different accounts gives you different results. Don’t forget that you can always go to
/accounts/logout/ to sign out from your current user account.
The superuser is both staff and a superuser and can also see the view. The
manage.py createsuperuser command that you used to create the superuser automatically sets superuser accounts to be staff.
Under the covers, the
@login_required decorator actually calls the
@user_passes_test decorator and uses the following test. All the
@login_required decorator is doing is checking that the user’s
is_authenticated value is
True, which will be the case for any authenticated account.
Become a Member to join the conversation.