1

We have a project setup implemented in Django and we're trying to create a search function. Currently, we pass our database of users from view.py to our .html file (view.py code below)

def search(request):

template_name = "search/search_it.html"
users = models.Profile.objects.all()

context = {'users': users}
return render(request, template_name, context)

Inside of our html code is where we are having issues. We are able to read our passed in users as below.

{% if users %}
   <ul>
   {% for user in users %}

   <!--
   <script>
      var username = user.slug --> Does not recognize user object
      document.getElementById("a1").value = username;
   </script>
   -->

      <a id="test" value="/users/{{user.slug}}"></a>
   {% endfor %}
   </ul>
{% endif %}

Our issue is that we would like to compare the search input against each passed in user's name. Our html file uses a onclick button into javascript. We have decided to try to tackle this various ways including:

  1. Use the javascript value outside of the <script></script> - Did not work for obvious scope reasons
  2. Try to load the names into strings and then grab each name inside of the javascript - Messy and not proficient

and (what we would like to do)

  1. Load each user into a javascript array that can be used by our search function inside of our array.

We have spent a lot of time searching for similar questions with no avail. Where we are having the most trouble comprehending is how to grab the user data from

{% for user in users %}

and pass that into javascript to add to an array. Any help would be wonderful.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
ProNet
  • 21
  • 2

0 Answers0