在Django中返回其他上下文变量

时间:2011-04-28 03:36:03

标签: python django

我有一个用户可以搜索其他用户的页面,一旦他们搜索,就会显示符合其搜索条件的用户列表。在搜索结果中的每个用户旁边,我有一个“添加为朋友”的链接。每个链接都链接到urls.py文件中的python函数,该函数会将请求添加到数据库等。但是,我没有使用AJAX为此我正在尝试制作我可以使用或不使用JavaScript的所有内容。但是一旦调用python函数,我想将一个上下文变量返回给调用该函数的模板并添加一个变量我可以在模板中检查它并删除用户单击的链接,但将所有其他链接留在所有其他用户旁边.python功能如下:

def request_friend(request,to_friend):
    try:
        from_friend = request.user
        to_friend = CustomUser.objects.get(pk=to_friend)
        f = Friendship(from_friend=from_friend,to_friend=to_friend)
        f.save()
        f1 = Friendship(from_friend=to_friend,to_friend=from_friend)
        f1.save()
        try:
            text = "<a href='/%s/'>%s</a> has requested you as a friend" % (from_friend.username,from_friend.username)
            n = Notification(from_user=from_friend,to_user=to_friend,notification_text=text)
            n.save()
            response = 'Friend Requested'
        except:
            response = 'Couldnt save notification'
    except:
        response = 'Did not save to database'
    return TemplateResponse(request,'users/friend_search.html',{'friend_added':response})

显示用户列表的模板代码如下:

{% for u in users %}
<div id="results">
    <img src="{{ u.profile_pic }}" class="xsmall-pic" /> <a href="/{{ u.username }}/">{{ u.username }}</a><br />
    <span class="small-date">{{ u.get_full_name }}</span>
    <span class="floatR" id="user_{{ u.id }}_link">{% if not friend_added %}<a href="/users/requests/friends/{{ u.id }}/" id="{{ u.id }}" class="user_link" onclick="return request_friend({{ u.id }});">Add as friend</a>{% else %}{{ friend_added }}{% endif %}</span>

</div>{% endfor %}

我怎样才能做到这一点?感谢

2 个答案:

答案 0 :(得分:1)

我没有完全理解您在代码中缺少的变量,而是将变量添加到上下文中 你有render_to_response非常方便。如果您需要整个站点上的变量,请在上下文字典中手动添加所需内容,或使用context_processors

答案 1 :(得分:0)

以下代码完成工作。相应地调整模板。

def request_friend(request,to_friend):
    result = False
    try:
        from_friend = request.user
        to_friend = CustomUser.objects.get(pk=to_friend)
        f = Friendship(from_friend=from_friend,to_friend=to_friend)
        f.save()
        f1 = Friendship(from_friend=to_friend,to_friend=from_friend)
        f1.save()
        try:
            text = "<a href='/%s/'>%s</a> has requested you as a friend" % (from_friend.username,from_friend.username)
            n = Notification(from_user=from_friend,to_user=to_friend,notification_text=text)
            n.save()
            response = 'Friend Requested'
            result = True
        except:
            response = 'Couldnt save notification'
    except:
        response = 'Did not save to database'
    return TemplateResponse(request,
                            'users/friend_search.html',
                            {
                            'friend_added': result, 
                            'message': response
                            })