[英]create custom decorator in django based on url paramenters
I have two login urls: 我有两个登录网址:
And I have a view, 我有一个看法,
@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)
And my two urls are: 我的两个网址是:
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'),
Now my question is, I want a decorator instead of @login_required
say @custom_login_required
, in which if the user is not authenticated and going to url /favorites/ here mode=None
, it should be redirected to url /profile/login/
. 现在我的问题是,我想要一个装饰器而不是@login_required
说@custom_login_required
,其中如果用户未通过身份验证并转到url /favorites/ here mode=None
,则应将其重定向到url /profile/login/
。
And if he is going to url /mob/favorites/
(here mode='mob')with out authentication he should be redirected to login url /mob/profile/login/
. 如果他未经身份验证即转到url /mob/favorites/
(此处为mode ='mob'),则应将其重定向到登录url /mob/profile/login/
。
Any help is highly appreciated. 非常感谢您的帮助。 If the question not clear please comment. 如果问题不清楚,请发表评论。
My self created a custom decorator for the same, 我自己为此创建了一个自定义装饰器,
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
here settings.MOBILE_LOGIN_URL
is /mob/profile/login/
and settings.LOGIN_URL
is /profile/login/
在这里settings.MOBILE_LOGIN_URL
是/mob/profile/login/
和settings.LOGIN_URL
是/profile/login/
Here I used the function django.contrib.auth.decorators.user_passes_test
with relevant modification. 在这里,我使用了带有相关修改的django.contrib.auth.decorators.user_passes_test
函数。 But still I am unaware how can we reuse the django built-in decorator @login_required
for the same. 但是我仍然不知道我们如何才能重复使用django内置装饰器@login_required
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.