在我的Django项目中,我必须从 forms 中获取输入并将其作为 views.py 中的函数的参数传递。我该怎么办?
我的views.py代码
from django.shortcuts import render,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from search_engine import query
from .forms import SearchForm
def query_input(request):
if request.method == "POST":
form = SearchForm(request.POST)
else:
form = SearchForm()
return render(request, 'search.html', {'form': form})
def search_results(request):
search_results = query.results(# text input from forms)
a = "<br /><br />".join(word for word in search_results)
return HttpResponse(a)
我的forms.py代码
from django import forms
class SearchForm(forms.Form):
your_query = forms.CharField(max_length=100)
答案 0 :(得分:1)
在检查request方法是POST之后,您可以验证表单,然后像这样访问其属性
在views.py中:
if request.method = "POST":
form = SearchForm(request.POST)
if form.is_valid():
search_text = form.cleaned_data['search_text']
# code from search_results function to return HTTP Response
请查看表单文档,并查看here以获取更多信息。