简体   繁体   中英

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?

修复dispath的错字,并使用is_authenticated()代替is_anonymous (如上一个答案所示)

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.

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):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM