TIL/2020–12–1

Renzo Regio
3 min readDec 13, 2020

--

Today I will talk about customizing or creating your own mixin as well as the LoginRequiredMixin.

We want to create a mixin that doesn’t allow people to access paths that they don’t need to access or the paths that they shouldn’t be able to access. For example, if you are logged in you wouldn’t need to access the login page or signup page. Or if you are logged out you shouldn’t be able to access change password or update profile. We can protect/restrict these paths by using mixins.

To create a mixin, we would need to create a “mixins.py” in our application. We wouldn’t have to create a mixin from scratch but customize a mixin by making use of UserPassesTestMixin.

First let’s work on our views that can only be accessed while logged out:

  1. Import: from django.contrib.auth.mixins import UserPassesTestMixin.

UserPassesTestMixin as what the name implies is that if the user passes the test/if it returns true then it moves on to the next argument. In this case, UserPassesTestMixin always requires the test_func — test function.

So if the user is not authenticated(not logged in) it will proceed to the form, else it will proceed to the handle_no_permission. Note: handle_no_permission and test_func aren’t names that were made up by me. It is the actual method of the mixins.

handle_no_permission is only executed if test_func returns False. If test_func returns True then handle_no_permission will not be executed, instead it will move forward to the form.

To add the custom mixin: LoggedOutOnlyView to my CBV we first have to import the mixin from the mixins.py. Or just import mixins altogether.

To add it, just place it on the CBV’s arguments. There is a flow to it, you cannot just add it anywhere. The flow is that in LoginView, if a user tries to access LoginView in the url by doing users/login while logged out or logged in, mixins.LoggedOutOnlyView will take effect either way. It is the first one that is called whenever a user tries to access the path.

Let’s say that I am logged in then I try to access the path of the CBV above. The first argument, mixins.LoggedOutOnlyView, will take effect and check if the user is logged out. Since I am logged in then test_func will return False and it will automatically call handle_no_permission and execute the error message and redirect me to core:home.

But if I am logged out, mixins.LoggedOutOnlyView is still called and test_func will then return True. Since it will return True, handle_no_permission will not be executed and I will be able to access the Login form.

On the next one, I will do LoggedInOnlyView. As you can see mixins definitely are powerful and using mixins would also improve the functionality of the website and protect the website at the same time. Using LoggedOutOnlyView will now protect the views that should only be viewed when logged out.

--

--

No responses yet