如何从输入表单获取数据

时间:2019-08-17 15:39:09

标签: python django forms

我需要从输入中获取数据并将其写入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

1 个答案:

答案 0 :(得分:0)

我们将需要更改index()函数以处理POSTGET方法(有关GET和{{1的更多信息,请参考https://www.w3schools.com/tags/ref_httpmethods.asp }}请求),默认情况下django总是监听POST请求。通过为GET使用GETrequest.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请求。