1

I am creating an app using django where an user can search for definition of some things. So f.e. he is inputing a word "security" to get definition of this. He gets results and then he is pushing back button. And then he gets a website, but the search-field still stores the old data/input "security". How can i fix this?

template:

<div>
    <h1><a href="/">Drink drank drunk</a></h1>
</div>
<h1>Jakie masz skladniki?</h1>

<form action="{% url 'search_results' %}" method="get">
  <input name="q" type="text" placeholder="Search...">
</form>
{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}

views:

from django.shortcuts import render
from django.db.models import Q #new

from .models import Recipe
from .models import Ingredient

from django.contrib import messages
from django.shortcuts import redirect

def drink_list(request):
    template = "drinks/drink_list.html"
    return render(request, template)

def search_results(besos):

    query = besos.GET.get('q')
    if not query or query == ' ' or query == '  ' or query == '   ':
    #how to write this ^  in shortest way? if string is empty then return 'drink_list'
        messages.error(besos, "Search field can not be empty")
        return redirect('drink_list')

    else:
        q = Q()
        for queries in query.split():
            q |= (Q(ingredients__ingredient_name__icontains=queries))
            #why it look for 'sok z cytryny' and show as well sok z limonki
        results = Recipe.objects.filter(q)
        template = "drinks/search_results.html"
        context = {
        'results' : results,
        }
        return render(besos, template, context)

URL:

urlpatterns = [
    path('', views.drink_list, name='drink_list'),
    path('search/', views.search_results, name='search_results'),
    path('no_name/', views.drink_list, name='drink_list'),
]

2 Answers2

0

What about trying this with some javascript? You can blank out the input tag on pageload.

<script>
    window.onload = function(){
                        document.getElementByName("q").value = "";
                    }
</script>

Or you can try this

<script>
    if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
        document.getElementByName("q").value = "";
    }
</script>
Matt Cremeens
  • 4,951
  • 7
  • 38
  • 67
0

Try this

<button onclick="history.back()">Go Back</button>

Clicking Go Back.get previous sections without clear inputs..

enes islam
  • 1,054
  • 4
  • 12
Vishnu T s
  • 11
  • 1