So I created a form. In this form, I make GET requests to the server to search for particular users. The view responsible for using the query words returns a template as follows.
html with the form
<a href="{% url 'logout'}">Logout</a>
<p>Welcome</p>
<form id="search" method="GET" action="{% url 'results' %}" placeholder= "Choose a friend"
autocomplete="off">
{{form}}
<input type="submit" value="search" name="search">
</form>
<a href="{% url 'liked' %}"> View Liked Songs</a>
{% endblock %}
`views to handle data passed into the form`
def results(request):
if request.method == "GET":
search_query = request.GET.get("username")
searched_user = UserProfile.objects.filter(
user__username__contains=search_query
)
return render(
request, "searched_results.html", {
"searched_user":searched_user
})
else:
return HttpResponse("Search returned nothing")
This is where the issue is. Now I have two HTML files. One ought to display data returned in the results view but I want it displayed only wheni click a button in the other HTML file. This is what I mean;
I have this HTML file which is rendered when the results/
route is used.
{% extends "base.html" %}
{% block spotify %}
{%if searched_user %}
{% for each_searched_user in searched_user %}
<br/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}}<br/>
{% endfor %}
{% endfor %}
{% endif %}
{% endblock %}
But I want the results endpoint to return an HTML with a button. And then, that button triggers the HTML file above to be displayed. I decided to use AJAX and create a separate html
endpoint for the HTML above and have the results
endpoint return toggle.html
then I use JS to get the html
endpoint and fill the empty div but all to no avail. How do I achieve this?
def html(request):
return render(request,
template_name= "search_results.html"
)
// toggle.html
{% extends "base.html" %}
{% block spotify %}
<div id="container">
</div>
<button id=likedsongsbutton>View liked songs</button>
<script>
var request = new XMLHttpRequest();
const container= document.getElementById("container")
request.onload = function() {
if (this.status == 200) {
document.querySelector("#likedsongsbutton").addEventListener("click",
() => container.innerHTML = request.responseText
);}
else{
console.warn("error");
}};
request.open('GET', '{% url "html" %}', true);
request.send();
</script>
{% endblock %}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…