Note that there are some explanatory texts on larger screens.

plurals
  1. POreturning additional context variables in Django
    text
    copied!<p>I have a page that users can search for other users on and once they search, a list of users is displayed that match their search criteria. Next to each user in the search results, I have a link to "Add as friend'. Each link is linked to a python function in the urls.py file that will add the request to the database etc. However, I am not using AJAX for this as of yet as I am trying to make everything that I can work with or without JavaScript. But once the python function is called, I want to return a context variable back to the template that called the function and add a variable so that I can check for it in the template and remove the link that the user clicked but leave all other links next to all other users. The python function is below:</p> <pre><code>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 = "&lt;a href='/%s/'&gt;%s&lt;/a&gt; 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}) </code></pre> <p>And the template code that shows the list of users is below:</p> <pre><code>{% for u in users %} &lt;div id="results"&gt; &lt;img src="{{ u.profile_pic }}" class="xsmall-pic" /&gt; &lt;a href="/{{ u.username }}/"&gt;{{ u.username }}&lt;/a&gt;&lt;br /&gt; &lt;span class="small-date"&gt;{{ u.get_full_name }}&lt;/span&gt; &lt;span class="floatR" id="user_{{ u.id }}_link"&gt;{% if not friend_added %}&lt;a href="/users/requests/friends/{{ u.id }}/" id="{{ u.id }}" class="user_link" onclick="return request_friend({{ u.id }});"&gt;Add as friend&lt;/a&gt;{% else %}{{ friend_added }}{% endif %}&lt;/span&gt; &lt;/div&gt;{% endfor %} </code></pre> <p>How can I accomplish this? Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload