intelis
intelis

Reputation: 8068

Django mixin not working as expected

I want to prevent logged-in users to access login and register forms.
I've build custom mixin, but it isn't working. The problem is that even if the user is logged in, he can access login and register forms instead of beeing redirected to homepage.

My Mixin

class MustBeAnonymousMixin(object):
    ''' Only anonymous users (not logged in) may access login and register
    '''

    def dispath(self, *args, **kwargs):
        if not self.request.user.is_anonymous:
            return redirect(reverse('homepage'))
        return super(MustBeAnonymousMixin, self).dispatch(*args, **kwargs)

LoginFormView

class LoginFormView(MustBeAnonymousMixin, TemplateView):
    '''
    Display basic user login form
    '''
    template_name = 'members/login.html'

    def get_context_data(self, **kwargs):
        context = super(LoginFormView, self).get_context_data(**kwargs)
        context['login_form'] = UserLoginForm()
        return context

I'm using Django 1.8. What am I doing wrong?

Upvotes: 0

Views: 1085

Answers (3)

HoangYell
HoangYell

Reputation: 4661

For another case where mixin does not work:

Remember: "Mixin param" must stand before "GenericView param"

Correct:

class PostDelete(LoginRequiredMixin, generic.DeleteView):

Incorrect:

class PostDelete(generic.DeleteView, LoginRequiredMixin):

Upvotes: 3

Pynchia
Pynchia

Reputation: 11590

Fix the typo in dispath and use is_authenticated() instead of is_anonymous (as indicated in the previous answer already)

Upvotes: 2

NeoWang
NeoWang

Reputation: 18523

is_anonymous should be a function call, and you probably should not use it:

is_anonymous()

Always returns False. This is a way of differentiating User and AnonymousUser objects. Generally, you should prefer using is_authenticated() to this method.

Upvotes: 1

Related Questions