我需要从输入中获取数据并将其写入query
变量中。当我单击搜索按钮时,我需要在查询变量中写入数据。我怎样才能做到这一点?我的意思是单击事件并在query
中写入数据。
这是我的代码:
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'index.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")
for j in search(search_query, tld="co.in", num=10, stop=1, pause=2):
print(j)
else:
return HttpResponse('Invalid input.')
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
urls.py
from django.urls import path
from firstapp import views
urlpatterns = [
path('', views.index, name='home')
]
所有文件都位于hello
文件夹中。我的应用是firstapp
path:
C:\Users\user\Desktop\hello\firstapp
index.html
的路径是:
C:\Users\user\Desktop\hello\firstapp\templates
答案 0 :(得分:0)
我们将需要更改index()
函数以处理POST
或GET
方法(有关GET
和{{1的更多信息,请参考https://www.w3schools.com/tags/ref_httpmethods.asp }}请求),默认情况下django总是监听POST
请求。通过为GET
使用GET
和request.method == 'GET'
,可以知道方法是否为request.method == 'POST'
。
要访问方法中的数据,请使用POST
,该方法基本上说是从表单中找到具有request.POST.get("search", None)
属性的输入,或者如果输入不存在,则返回name
。
因此,总的来说,您的代码现在应该像这样
None
现在在应用程序内部,创建一个名为from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'home/home.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
# Implement search functionality....
# ...
return HttpResponse(search_query)
else:
print("Invalid input")
return render(request, 'home/home.html', context={})
的文件夹并添加templates
index.html
文件应如下所示(要了解有关模板的更多信息,请参见:https://docs.djangoproject.com/en/2.2/topics/templates/):
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
此外,如果您查看my_app/templates/index.html
标签,则会发现一个<form>
标签,上面写着method
。这表明正在提交的数据是否为POST
请求。