我有一個頁面,用戶可以搜索其他用戶,一旦他們搜索,就會顯示一個符合其搜索條件的用戶列表。在搜索結果中的每個用戶旁邊,我有一個「添加爲朋友」的鏈接。每個鏈接都鏈接到urls.py文件中的一個python函數,它將請求添加到數據庫等。但是,我沒有使用對於這個AJAX來說,我試圖讓所有可以使用或不使用JavaScript的東西都可以使用,但是一旦調用了python函數,我想要返回一個上下文變量回調用函數的模板並添加一個變量我可以在模板中檢查並刪除用戶點擊該鏈接,但保留其他所有旁邊的鏈接所有其他用戶Python函數是下面:在Django中返回附加的上下文變量
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="https://stackoverflow.com/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 %}
我該如何做到這一點?謝謝