天天看點

将對象交給前台

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