目前,我尝试为一个小型数据库制作一个搜索表单。
这是我的 models.py 文件的一部分:
from django.db import models
from django import forms
#...
class searchForm(forms.Form):
searchField = forms.CharField(max_length = 100)
#...
这是我的 views.py 文件的一部分:
from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
#...
def index(request):
template = loader.get_template('index.html')
context = Context({})
return HttpResponse(template.render(context))
def search(request):
if request.method == 'POST': # If the form has been submitted...
form = searchForm(request.POST)# A form bound to the POST data
if form.is_valid():
searchData = form.cleaned_data['searchField']
return HttpResponseRedirect('search.html') # Redirect after POST #???
else:
searchData = searchForm() # an unbound form
return render(request, 'search.html', {'form': form,}) #???
#...
这是我的 index.html 的一部分,我想在其中实现该表单:
<label for="Search">Search:</label>
<form action = "/search/" method = "post">
{% csrf_token %} {{ form.as_p }}
<input type = "submit" value = "Go" />
</form>
我正在尝试做的事情:
当我提交表单时,我想重定向到名为 search.html 的结果文件,其中首先显示来自搜索文本字段的输入。链接结构应该是这样的:
登陆页面是:http://127.0.0.1:8000/
在提交表单之后:http://127.0.0.1:8000/search.html
我认为搜索方法可能有错误,我用'???'标记了这些行。下一个问题是,我的搜索文本字段没有出现。
如果有人能给我一些建议,那就太好了。
谢谢,埃尔约索