mar*_*len 5 python django django-urls django-views
我想将一个int参数(user_id)从登录视图传递到另一个视图.这可能在一个HttpResponseRedirect?我尝试这样的事情:
return HttpResponseRedirect("/profile/?user_id=user.id")
Run Code Online (Sandbox Code Playgroud)
虽然我的urlconf是:
(r'^profile/(?P<user_id>\d+)/$', '...')
Run Code Online (Sandbox Code Playgroud)
但我不知道这是否正确.有什么建议?
嗯,这显然不是正确的方法,因为您创建的 URL 与 urlconf 中的 URL 不匹配。
正确的方法是依靠 Django 来为您完成此操作。如果您为 URL 定义指定一个名称:
urlpatterns += patterns('',
url(r'^profile/(?P\d+)/$', ' ...', name='profile'),
)
Run Code Online (Sandbox Code Playgroud)
然后您可以使用django.core.urlresolvers.reverse您的参数生成该 URL:
redirect_url = reverse('profile', args=[user.id])
return HttpResponseRedirect(redirect_url)
Run Code Online (Sandbox Code Playgroud)
请注意,最好在 URL 中使用 kwargs 而不是 args,但我将其保留为原来的样子。