Django:重定向到带参数的视图 [英] Django: redirect to view with parameters
问题描述
我正在使用Django身份验证.每当用户登录时,我都希望将他重定向到/profile/user_id,即user_id为数字.我可以通过request.user.profile.id
获取user_id的值.在settings.py中,我有LOGIN_REDIRECT_URL = 'app_1:index'
I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id
. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index'
app_1/urls.py:
app_1/urls.py:
url(r'^profile/$', views.index, name='index'),
# ex: /profile/5/
url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'),
app_1/views.py(我也尝试过的事情得到评论):
app_1/views.py (things I've also tried are commented):
def index(request):
userid = request.user.profile.id
#return render(request, 'app_1/index.html', context)
#return profile(request, request.user.profile.id)
#return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id})
#return redirect(profile, user_id= request.user.profile.id)
return redirect('profile', user_id=userid)
def profile(request, user_id):
user = get_object_or_404(Profile, pk=user_id)
return render(request, 'app_1/user_prof.html', {'user': user})
我一定想念一些东西,因为这应该很容易,但是我坚持下去.预先感谢.
I must be missing something because this should be easy but I'm stuck on it. Thanks in advance.
我遇到的错误是Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.
: http://dpaste.com/270YRJ9
推荐答案
尝试改用此
from django.urls import reverse
return redirect(reverse('profile', kwargs={"user_id": userid}))
编辑
那又如何:return redirect('app_1:profile', user_id=userid)
这篇关于Django:重定向到带参数的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!