0
votes

I am implementing a search function. I can get it to work fine if I just do an 'if search' in each view and render it on each page but I know there is a better way. I want the search submit button to render a results page. I can see the search request in the URL but why is my search function not being called?

I have tried moving the 'action' attribute from the form class to the button class to the form control class. I have tried replacing the action attribute with an href attribute. It does not seem to run my function.

path('results/', views.search, name='search'),


def search(request):
print('here!')
eqs = Equipment.objects.all()
locs = Location.objects.all()
if 'search' in request.GET:
    search_term = self.request.GET['search']
#    searching = Equipment.objects.filter(name__icontains=search_term)
    searching = sorted(
        chain(eqs, locs)
    )
    context['search_term'] = search_term
    context['searching'] = searching
return render(
    request,
    'results.html',
    context = {
        'search_term': search_term,
        'searching': searchin,
    }
    )


<form class="form-inline my-2 my-lg-0" action="{% url 'search' %}">
    <input class="form-control mr-sm-2"
           type="search"
           placeholder="Search"
           aria-label="Search"
           name="search">
    <button class="btn btn-outline-success my-2 my-sm-0 search-button"   role="button" type="submit">Search</button>
  </form>'''

I am not getting any errors, the search field is being captured, but I just stay on the page and the function does not appear to run.

1

1 Answers

1
votes

Your form is sending a POST and then you are trying to retrieve the value from request.GET in your view. You need to add method="GET" to your form.

You can learn more about form data at : https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data#The_GET_method

You can learn more about Django request handling at:https://docs.djangoproject.com/en/2.2/ref/request-response/#httprequest-objects

EDIT: Upon reading further into your question and looking at your code. It is coming from having role="button" in your submit button. Change that and you should be good to go. This question shares more information: Do I need role="button" on a <button>? (This could be wrong as well though) It would be really helpful to get a console log or something.