0

我如何将“if request.user.is_authenticated”插入到下面的表单向导类中,如下例所示?这个想法是这个视图是我的主页,如果用户已经登录,我想重定向到另一个页面。

目前它给我“名称'请求'未定义”作为错误消息。我尝试了 BusinessWizard(request, SessionWizardView) 类,但不幸的是它不起作用。也许这是我的一个简单的疏忽。感谢您的帮助!

视图.py

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

1 回答 1

2

最简单的方法是在 urlconf中添加login_required user_passes_test 装饰器:

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())),
)

参考:
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

如果要定义自己的装饰器,可以使用以下代码段:

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())),
)
于 2013-01-28T01:40:43.127 回答