Warm tip: This article is reproduced from serverfault.com, please click

其他-Django重定向URL包含ID

(其他 - django redirect url containing id)

发布于 2010-06-03 11:07:24

我想在我的settings.py中添加如下声明:

LOGIN_REDIRECT_URL='^private_profile/(?P<id>\d+)/$'
#or 
LOGIN_REDIRECT_URL='/accounts/private_profile/id/'

这样,当ID为1的用户登录时,他将被重定向到

LOGIN_REDIRECT_URL='/accounts/private_profile/1/'

但两种选择

LOGIN_REDIRECT_URL='^private_profile/(?P<id>\d+)/$'
#or 
LOGIN_REDIRECT_URL='/accounts/private_profile/id/'

是错误的,因为在我的浏览器中我看不到当前的用户ID,我在哪里错了?谢谢

Questioner
dana
Viewed
0
KillianDS 2010-06-03 19:17:00

实现此目的的一个技巧是为每个人定义一个通用视图并将其链接到该视图,然后该视图应类似于:

from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required
def after_login(request):
    return HttpResponseRedirect('/accounts/private_profile/%d/'%request.user.id)

但是,正如我在评论中所述,只有在你确实要在网址中使用用户ID的情况下,这在大多数情况下根本没有必要。在我看来,你可以从请求上下文中获取用户ID,前提django.contrib.auth.context_processors.auth该用户ID已添加到TEMPLATE_CONTEXT_PROCESSORSsettings.py中的设置中