Search code examples
djangoauthenticationformwizard

How do I insert a login if statement into FormWizard View for Django?


How would I insert "if request.user.is_authenticated" into the form wizard class below like shown in the example below? The idea is this view is my homepage and I would like to redirect to a different page if the user is already logged in.

Currently it is giving me "name 'request' is not defined" as an error message. I tried class BusinessWizard(request, SessionWizardView), but unfortunately it did not work. Maybe it is a simple oversight on my part. Thank you for your help!

views.py

class BusinessWizard(SessionWizardView):
      if request.user.is_authenticated:
          HttpResponseRedirect('some url')
      else:
          #some code and functions etc

Solution

  • The easiest way is to add the login_required user_passes_test decorator in the urlconf:

    from django.conf.urls import patterns
    from django.contrib.auth.decorators import user_passes_test
    from .views import BusinessWizard
    
    urlpatterns = patterns('',
        (r'^wizard/$', user_passes_test(lambda user: user.is_anonymous(), 'some url', None)(BusinessWizard.as_view())),
    )
    

    Reference:
    https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-in-urlconf
    https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.decorators.user_passes_test

    If you want to define your own decorator you can use the following snippet:

    from functools import wraps
    from django.conf.urls import patterns
    from django.http import HttpResponseRedirect
    from .views import BusinessWizard
    
    def anonymous_required(redirect_url=None):
        """
        Decorator that redirects authenticated users to a different URL.
        """
    
        def decorator(view_func):
            @wraps(view_func, assigned=available_attrs(view_func))
            def _wrapped_view(request, *args, **kwargs):
                if request.user.is_anonymous():
                    return view_func(request, *args, **kwargs)
                return HttpResponseRedirect(redirect_url)
            return _wrapped_view
        return decorator
    
    urlpatterns = patterns('',
        (r'^wizard/$', anonymous_required('some url')(BusinessWizard.as_view())),
    )