简体   繁体   中英

How do I get user input from search bar to display in a page? Django

Django is very challenging and I still need to get used to the code and currently, I just want the search bar to display every time a user input a text and it will display like a title I really don't how to interpret the code to tell that every time the user inputs in the search bar, It is supposed to display the user input on a page like a title.

Example: user input in the search bar: cat and it displays cat title

Display on the current page:

Result search: "Cat"

HTML Code

<!-- Search Bar -->
<form action="{% url 'enc:search' %}" method="GET">
  {% csrf_token %}
  <input class="search" type="text" name="q" placeholder="Search">
</form>

In my views.py I only write this code and I don't know what to write it.

views.py

def search (request):
    title = request.GET.get("q", "")

urls.py

urlpatterns = [
    path("", views.index, name="index"),
    path("search/", views.search, name="search"),

Right now just a simple display from the search bar input later I will code it in a data search where there is some file to integrate the search but right now I really need some help my brain is cracking. It's kinda sad I mean I know it be a simple code but I don't know why I can't figure it out.

please do help me if you have tips on how to be better on Django and python too it be much help for me and thank you for your time I really appreciate it very much.

searchpage.html:

<!-- Search Bar -->
<form action="{% url 'enc:search' %}" method="POST">
  {% csrf_token %}
  <input class="search" type="text" name="q" placeholder="Search">
  <input type="submit" value="Submit">
</form> 

views.py:

from django.shortcuts import render

def search (request):
    #defines what happens when there is a POST request
    if request.method == "POST":
        title = request.POST.get("q")
        return render(request,'new_template.html', { 'title' : title })


    #defines what happens when there is a GET request
    else:
        return render(request,'searchpage.html')

new_template.html:

<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>search term</title>
</head>
<body>

<h1> {{ title }} </h1>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM