0

我有两个登录网址:

  1. /个人资料/登录/
  2. /mob/个人资料/登录/

我有一个看法,

@login_required
def favorited_spreads(request ,page_template='spreads/favorited_spreads_ajax.html',
        template='spreads/favorited_spreads.html',mode=None):
    profile = request.user.profiles
    spreads = profile.favorite_by.all()
    context = {
            'spreads': spreads,
            'profile': profile,
        }
    if request.is_ajax():
        template=page_template
    return render(request, template,context)

我的两个网址是:

 url(r'^favorites/$',
    'favorited_spreads', name='favorited_spreads'),
url(r'^mob/favorites/$',
        'favorited_spreads',{
               'template':'mobapps/spreads/favorited_spreads.html',"mode":"mob"}, name='favorited_spreads_mob'),

现在我的问题是,我想要一个装饰器而不是@login_requiredsay @custom_login_required,如果用户没有经过身份验证并转到 url /favorites/ here mode=None,它应该被重定向到 url /profile/login/

如果他要在/mob/favorites/没有身份验证的情况下访问 url(此处为 mode='mob'),他应该被重定向到 login url /mob/profile/login/

非常感谢任何帮助。如果问题不清楚,请发表评论。

4

1 回答 1

0

我自己为此创建了一个自定义装饰器,

def custom_login_required(function,redirect_field_name=REDIRECT_FIELD_NAME):
    def wrapped_func(request,mode=None, *args,**kwargs):
        login_url=settings.MOBILE_LOGIN_URL if mode else settings.LOGIN_URL
        if request.user.is_authenticated():
            return function(request, mode=mode,*args, **kwargs)
        path = request.build_absolute_uri()
        # If the login url is the same scheme and net location then just
        # use the path as the "next" url.
        login_scheme, login_netloc = urlparse.urlparse(login_url or
                                                    settings.LOGIN_URL)[:2]
        current_scheme, current_netloc = urlparse.urlparse(path)[:2]
        if ((not login_scheme or login_scheme == current_scheme) and
            (not login_netloc or login_netloc == current_netloc)):
            path = request.get_full_path()
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(path, login_url, redirect_field_name)
    return wrapped_func

这里settings.MOBILE_LOGIN_URL是现在/mob/profile/login/_settings.LOGIN_URL/profile/login/

这里我使用了django.contrib.auth.decorators.user_passes_test相关修改的功能。但我仍然不知道我们如何重用 django 内置装饰器@login_required

于 2013-07-26T08:35:46.547 回答