0

I need to pass the form input entered by the user to the URL variable in Django

<form>
          <div class="input-group">
            <input type="text" name="ticker" class="form-control" placeholder="Search">
            <div class="input-group-btn">
              <a her="{% url 'Main:search' %}" class="btn btn-default">
                <i class="bi bi-search"></i>
              </a>
            </div>
          </div>
        </form> 

The input value needs to be passed as a variable in the following URL logic

"{% url 'Main:search' %}"

urls.py

app_name = 'Main'
urlpatterns = [
    path("", views.index, name='index'),
        path('search/<ticker>', views.search, name='search'),
]

views.py

def search(request, ticker):
    ticker = ticker.upper()
    result = Symbol.objects.filter(symbol=ticker).first()
    if result is not None:
        return redirect('Symbol:index', ticker=ticker)
    else:
        return render(request, 'symbol_not_found.html')
1
  • <a her="{% url 'Main:search' %}" What is her=? Did you mean href=? Commented Mar 11, 2024 at 1:27

1 Answer 1

0

try this out:

the_view.html:

<form>
    <div class="input-group">
    <input type="text" name="ticker" class="form-control" placeholder="Search">
    <div class="input-group-btn">
        <a herf="{% url 'Main:search' ticker %}" class="btn btn-default">
        <i class="bi bi-search"></i>
        </a>
    </div>
    </div>
</form> 

urls.py



app_name = 'Main'
urlpatterns = [
    path("", views.index, name='index'),
        path('search/<str:ticker>', views.search, name='search'),
]

views.py

from django.shortcuts import get_list_or_404
from django.urls import reverse

def search(request, ticker):
    result = get_list_or_404(Symbol, symbol=ticker) # If list is empty 404
    result = result[0] # get the first element in the list
    return render(request, reverse('Symbol:index',args=(ticker=ticker,)))

To get more info, you should make the small intro project in Django Docs, especially this part.

Sign up to request clarification or add additional context in comments.

2 Comments

I get the following error Reverse for 'search' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<ticker>[^/]+)\\Z']
first edit the function name in views, I misspelled it, it is search not results

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.