【问题标题】:Django: redirect to view with parametersDjango:重定向到带有参数的视图
【发布时间】:2018-05-23 16:35:24
【问题描述】:

我正在使用 Django 身份验证。每当用户登录时,我想将他重定向到 /profile/user_id,因为 user_id 是一个数字。我可以通过request.user.profile.id 获取user_id 的值。在 settings.py 我有LOGIN_REDIRECT_URL = 'app_1:index'

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(我也尝试过的东西被评论了):

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})

我一定遗漏了一些东西,因为这应该很容易,但我坚持下去。提前致谢。

编辑:我得到的错误是 Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9

【问题讨论】:

    标签: python django authentication


    【解决方案1】:

    尝试改用这个

    from django.urls import reverse
    
    return redirect(reverse('profile', kwargs={"user_id": userid}))
    

    编辑

    怎么样:return redirect('app_1:profile', user_id=userid)

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 2013-05-27
      • 1970-01-01
      • 2018-12-30
      • 2012-01-25
      • 1970-01-01
      • 2018-12-11
      • 2010-11-23
      • 1970-01-01
      相关资源
      最近更新 更多