我正在按照教程添加Django中的朋友:Building Friend Networks
我得到一个404页面,因为如果在request.GET中找不到用户名,我已经在我的代码中设置了它来引发Http404:
views.py:
def friend_add(request):
if 'username' in request.GET:
friend = get_object_or_404(User, username=request.GET['username'])
friendship = Friendship(from_friend=request.user, to_friend=friend)
friendship.save()
return HttpResponseRedirect('/friends/%s' % request.user.username)
else:
raise Http404
urls.py:
url(r'^friend/add/(?P<username>\w+)$', photo.views.friends_request),
url(r'^friends/(?P<username>\w+)$', photo.views.friends),
url(r'^request_sent/$', photo.views.friend_add),
我正在使用这样的模板标签,如教程所示:
{% ifequal user.username abuild.user %}
<a href="/builds/friends/{{ user.username }}">view your friends</a>
{% else %}
{% if is_friend %}
<a href="/builds/friends/{{ abuild.user }}">
{{ abuild.user }} is a friend of yours</a>
{% else %}
<a href="/builds/request_sent/">
add {{ abuild.user}} to your friends</a>
{% endif %}
- <a href="/builds/friends/{{ abuild.user }}">
view {{abuild.user}}'s friends</a>
{% endifequal %}
当我点击/request_sent/
的链接时,如何确保获取用户名?
abuild.user
是我要添加的用户,而user.username
是登录的用户。
答案 0 :(得分:1)
您应该像在其他情况下那样在网址中传递用户名。
因此,您的模板将更改为
<a href="/builds/request_sent/{{abuild.user.username}}">
urls.py将更改为
url(r'^request_sent/(?P<username>\w+)$', photo.views.friend_add),
然后视图将变为
def friend_add(request, username):
if 'username' in request.GET:
....