3

I would like to create a Mixin which will: First - Check if a user is authenticated, if not, redirect to login url. If yes... Second - Check if user has a defined Profile (a user), if not, redirect to Profile creation, else, allow user to access the View.

I was planning to do sometinhg like:

class ProfileRequiredMixin(LoginRequiredMixin,PermissionRequiredMixin):
#TODO check how multiple inheritance works treating conflicting methods
'''This Mixin should first check if user is autheticated, if not,
redirect to login. If it is, check if it has a  profile. 
If it does not, redirect to profile creation url. If it has, allow
access to view.'''
pass

But I am confused as how to overwrite the handle_no_permission() and dispatch() methods.

pedrovgp
  • 767
  • 9
  • 23

1 Answers1

8

I solved the problem in the following way:

class TestIfHasProfileMixin(UserPassesTestMixin):
    '''This Mixin should first check if user has a profile. 
    If it does not, redirect to profile creation url. If it has, allow
    access to view.'''

    def test_func(self):
        try:
            Profile.objects.get(user=self.request.user)
            return True
        except Profile.DoesNotExist:
            return False

    def handle_no_permission(self):
        '''to:[login,Profile] will signup or create profiles'''
        if self.raise_exception:
            raise PermissionDenied(self.get_permission_denied_message())
        return redirect('users:create-profile')


class ProfileRequiredMixin(LoginRequiredMixin,TestIfHasProfileMixin):
    '''This Mixin should first check if user is autheticated, if not,
    redirect to login. If it is, check if it has a profile. 
    If it does not, redirect to profile creation url. If it has, allow
    access to view.'''
    pass

Now every view that requires a Profile inherits from ProfileRequiredMixin, which will first test for login (redirect to login creation if there is not) and after that check for Profile and redirect to Profile creation if none exists.

pedrovgp
  • 767
  • 9
  • 23