最简单的方法是在 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())),
)