我第一次尝试创建一个小型 django 应用程序。它只是一个基本页面,有两个表单,一个从数据库返回值的搜索表单(运行良好)和一个插入表单(问题)。在插入表单中,有三个文本字段要求数据库中新行的值。该应用程序称为“搜索器”。这是我的代码:
视图.py
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from searcher.models import Publisher
from django.db.models import Q
def search(request):
if "search" in request.GET:
value = request.GET['search']
results = Publisher.objects.filter(Q(city__contains=value) | Q(name__contains=value))
else:
value = "No term"
results = []
template = get_template("base.html")
html = template.render(Context({"value":value, "results":results}))
return HttpResponse(html)
def insert(request):
if "name" in request.POST:
for key in request.POST:
counter = 0
if key != '':
counter = counter + 1
if counter == len(request.POST):
row = Publisher(name=request.POST['name'], city=request.POST['city'], website=request.POST['website'])
row.save()
base.html
<html>
<body>
<form method = "GET" action = "">
<input type = "text" name = "search"><input type = "submit">
</form><br>
you searched for:{{value}}<br>
your results:
{% for result in results %}
<br>{{result}}<br>
{% endfor %}
<br><br>
<form method = "POST" action = "/test/insert/">
<input type = "text" name = "name" value = "name"><br>
<input type = "text" name = "city" value = "city"><br>
<input type = "text" name = "website" value = "website"><br>
<input type = "submit">
</form>
</body>
</html>
网址.py
from django.conf.urls import patterns, include, url
from searcher import views
urlpatterns = patterns('',
url(r'^test/$', views.search),
url(r'^test/insert/$', views.insert),
)
错误是说“/test/insert 的 ValueError 视图 searcher.views.insert 没有返回 HttpResponse 对象。” 由于我提交了插入表格。
我明白错误在说什么:抱歉,views.py 中的所有视图都必须返回要显示的内容。
首先这是为什么?
其次,完成插入表单的正确方法是什么?目前我已经设置了表单 action = "/test/insert/" 以便在 urls.py 中它可以识别插入表单已提交并调用函数插入,应该如何调用该函数?