1. HTML 表单定义的一个变量q,提交表单后,q的通过GET请求( method="get" )传给 /search/ 。
2.处理/search/ 的Django 视图( search() ),通过request.GET访问q的
node2:/tlcb/mysite/books#cat templates/books/search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render
from books.models import Book
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains=q)
return render(request, 'search_results.html',
{'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
mysql> select * from books_book;
+----+-------+------------------+--------------+
| id | title | publication_date | publisher_id |
+----+-------+------------------+--------------+
| 1 | aaa | 2018-02-19 | 1 |
| 2 | query | 2018-02-19 | 2 |
+----+-------+------------------+--------------+
2 rows in set (0.00 sec)
query
<QuerySet [<Book: Book object>]>
<class 'django.db.models.query.QuerySet'>
Internal Server Error: /search/
把对象传递个前台模板:
Quit the server with CONTROL-C.
111111111111
<QueryDict: {u'q': [u'aabbccdd']}>
111111111111
<QuerySet []>
def search(request):
print '111111111111'
print request.GET
print '111111111111'
print '222222222222'
print request.GET['q']
print '222222222222'
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
books = Book.objects.filter(title__icontains=q)
print books
print type(books)
return render(request, 'search_results.html',
{'books': books, 'query': q})
else:
return HttpResponse('Please submit a search term.')
在这段代码中,有几处要注意:
1.除了检查request.GET 中有没有 'q' 之外,我们还确保request.GET['q']不是空值,然后再把查询传给数据库
2.我们使用 Book.objects.filter(title__icontains=q)在图书表中查找所有书名中包含查询词条的书。
icontains 是一种查找类型,这个语句基本上相当于"获取所有书名中包含q的书,而且不区分大小写"
mysql> select * from books_book;
+----+-------+------------------+--------------+
| id | title | publication_date | publisher_id |
+----+-------+------------------+--------------+
| 1 | aaa | 2018-02-19 | 1 |
| 2 | quoto | 2018-02-19 | 2 |
+----+-------+------------------+--------------+
2 rows in set (0.00 sec)
node2:/tlcb/mysite/books#cat templates/books/search_results.html
{% for book in books %}
<li>{{ book.id }}</li>
<li>{{ book.title }}</li>
<li>{{ book.publication_date }}</li>
<li>{{ book.publication_id }}</li>
{% endfor %}
http://192.168.137.3:9000/search/?q=quoto
2
quoto
Feb. 19, 2018