简体   繁体   English

如何从搜索栏中获取用户输入以显示在页面中? Django

[英]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. Django 非常具有挑战性,我仍然需要习惯代码,目前,我只想在每次用户输入文本时显示搜索栏,它会像标题一样显示我真的不知道如何解释代码告诉每次用户在搜索栏中输入时,它应该像标题一样在页面上显示用户输入。

Example: user input in the search bar: cat and it displays cat title示例:用户在搜索栏中输入:cat 并显示 cat 标题

Display on the current page:在当前页面显示:

Result search: "Cat"结果搜索:“猫”

HTML Code HTML 代码

<!-- 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中我只写了这段代码,我不知道写什么。

views.py视图.py

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

urls.py网址.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.如果您有关于如何在 Django 和 python 上做得更好的提示,请帮助我,这对我有很大帮助,感谢您的宝贵时间,我非常感谢。

searchpage.html:搜索页面.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:视图.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:新模板.html:

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

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

</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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