我有两个登录网址:
我有一个观点,
@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_required
说@custom_login_required
,如果用户未经过身份验证并转到网址/favorites/ here mode=None
,则应将其重定向到网址/profile/login/
。
如果他要通过身份验证来定位/mob/favorites/
(此处为mode ='mob'),则应将其重定向到登录网址/mob/profile/login/
。
非常感谢任何帮助。如果问题不明确请评论。
答案 0 :(得分: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
。