URL页面重定向Django

时间:2013-10-10 16:26:38

标签: django django-views django-urls

我正在制作类似于twitter的应用程序。在每个人员个人资料页面上,有一个选项,供当前登录用户关注他们正在查看的个人资料页面。我有一个关注/取消关注按钮,但是,一旦点击它就会重定向到一个错误页面,但如果你回去刷新,你可以看到,如果你跟着它们,你现在正在取消它们。所以我的问题是,点击按钮后如何将其重定向到同一页面?

以下是我收到的错误:

*之后的_reverse_with_prefix()参数必须是序列,而不是Profile ...

/home/skybluep/thesite/panda/twitter/views.py跟随

65返回HttpResponseRedirect(反向('twitterindex:detail',args = profile))

我的观点:

@login_required
def follow(request, username): 
    profile = get_object_or_404(Profile, user__username=username)
    user_profile = get_object_or_404(Profile, user=request.user)
    user_profile.following.add(profile)
    user_profile.save()
    return HttpResponseRedirect(reverse('twitterindex:detail', args = profile))

@login_required
def unfollow(request, username):
    profile = get_object_or_404(Profile, user__username=username)
    user_profile = get_object_or_404(Profile, user=request.user)
    user_profile.following.remove(profile)
    user_profile.save()
    return HttpResponseRedirect(reverse('twitterindex:detail', args = profile))

我的应用网址

urlpatterns = patterns('',
url(r'^$', views.index, name='twitterindex'),
url(r'^detail/(?P<username>\w+)/$', views.detail, name='detail'),
url(r'^detail/(?P<username>\w+)/newpost/$', views.post, name='newpost'),
url(r'^detail/(?P<username>\w+)/follow', views.follow, name='follow'),
url(r'^detail/(?P<username>\w+)/unfollow', views.unfollow, name='unfollow'),

)

2 个答案:

答案 0 :(得分:2)

错误很清楚,你应该这样做:

return HttpResponseRedirect(reverse('twitterindex:detail', args=(profile.user.username,) ))

答案 1 :(得分:0)

试:return HttpResponseRedirect(reverse('twitterindex:detail', args = profile.user.username))。你也不需要user_profile.save()

更好的方法:

@login_required
def follow(request, username): 
    profile = get_object_or_404(Profile, user__username=username)
    user_profile = get_object_or_404(Profile, user=request.user)
    user_profile.following.add(profile)        
    return HttpResponseRedirect(reverse('twitterindex:detail', args = profile.user.username))

@login_required
def unfollow(request, username):
    profile = get_object_or_404(Profile, user__username=username)
    user_profile = get_object_or_404(Profile, user=request.user)
    user_profile.following.remove(profile)    
    return HttpResponseRedirect(reverse('twitterindex:detail', args = profile.user.username))