LoginRequiredMixin and UserPassesTestMixin login_url clash

658 views
Skip to first unread message

Igor Belo

unread,
Dec 15, 2016, 12:53:38 PM12/15/16
to Django users
Let me describe my scenario.

I got some views that I want to check two conditions before render:
  1. user is logged in
  2. user fulfilled account details form

If user is not logged in -> redirect to login page.
If user have not fulfilled its account details -> redirect to the form page.

I'm using the LoginRequiredMixin to check 1 and the UserPassesTest to check 2 and the problem is that both mixins use the same login_url attribute (or method if I implement get_login_url) and as my views include both mixins, it always takes the most-left mixin login_url.

Here's my code:
class LoginRequired(LoginRequiredMixin):
    login_url = 'website:join'
    redirect_field_name = None

class FulfillAccountRequired(UserPassesTestMixin):
    login_url = 'website:account-detail'
    
    def test_func(self):
        ...

class MyView(FulfillAccountRequired, LoginRequired, ListView):
    ...

Would be nice if there's a way to set a callable name for login_url (which after diving into mixins source I think is not possible).

Is there another clean way to go through?

Thanks,

Igor Belo

unread,
Dec 15, 2016, 5:16:20 PM12/15/16
to Django users
I came up with a solution by overriding the handle_no_permission method from the UserPassesTestMixin:

class FulfillAccountRequired(UserPassesTestMixin):
   
def test_func(self):
       
return self.request.user.account_completed

   
def handle_no_permission(self):
       
return redirect('website:account-detail')

Not an elegant solution at all but solved my problem. Wondering if it worths to open a pull request.
Well, hope it helps someone in the future.
Reply all
Reply to author
Forward
0 new messages