国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

Python的Django框架中的表單處理示例

2019-11-25 17:10:16
字體:
供稿:網(wǎng)友

組建一個(gè)關(guān)于書籍、作者、出版社的例子:

from django.db import modelsclass Publisher(models.Model):  name = models.CharField(max_length=30)  address = models.CharField(max_length=50)  city = models.CharField(max_length=60)  state_province = models.CharField(max_length=30)  country = models.CharField(max_length=50)  website = models.URLField()class Author(models.Model):  first_name = models.CharField(max_length=30)  last_name = models.CharField(max_length=40)  email = models.EmailField()class Book(models.Model):  title = models.CharField(max_length=100)  authors = models.ManyToManyField(Author)  publisher = models.ForeignKey(Publisher)  publication_date = models.DateField()

我們現(xiàn)在來創(chuàng)建一個(gè)簡(jiǎn)單的view函數(shù)以便讓用戶可以通過書名從數(shù)據(jù)庫(kù)中查找書籍。
通常,表單開發(fā)分為兩個(gè)部分: 前端HTML頁(yè)面用戶接口和后臺(tái)view函數(shù)對(duì)所提交數(shù)據(jù)的處理過程。 第一部分很簡(jiǎn)單;現(xiàn)在我們來建立個(gè)view來顯示一個(gè)搜索表單:

from django.shortcuts import render_to_responsedef search_form(request):  return render_to_response('search_form.html')

這個(gè)view函數(shù)可以放到Python的搜索路徑的任何位置。 為了便于討論,咱們將它放在 books/views.py 里。

這個(gè) 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>

而 urls.py 中的 URLpattern 可能是這樣的:

from mysite.books import viewsurlpatterns = patterns('',  # ...  (r'^search-form/$', views.search_form),  # ...)

(注意,我們直接將views模塊import進(jìn)來了,而不是用類似 from mysite.views import search_form 這樣的語句,因?yàn)榍罢呖雌饋砀?jiǎn)潔。)

現(xiàn)在,如果你運(yùn)行 runserver 命令,然后訪問http://127.0.0.1:8000/search-form/,你會(huì)看到搜索界面。 非常簡(jiǎn)單。

不過,當(dāng)你通過這個(gè)form提交數(shù)據(jù)時(shí),你會(huì)得到一個(gè)Django 404錯(cuò)誤。 這個(gè)Form指向的URL /search/ 還沒有被實(shí)現(xiàn)。 讓我們添加第二個(gè)視圖函數(shù)并設(shè)置URL:

# urls.pyurlpatterns = patterns('',  # ...  (r'^search-form/$', views.search_form),  (r'^search/$', views.search),  # ...)# views.pydef search(request):  if 'q' in request.GET:    message = 'You searched for: %r' % request.GET['q']  else:    message = 'You submitted an empty form.'  return HttpResponse(message)

暫時(shí)先只顯示用戶搜索的字詞,以確定搜索數(shù)據(jù)被正確地提交給了Django,這樣你就會(huì)知道搜索數(shù)據(jù)是如何在這個(gè)系統(tǒng)中傳遞的。 簡(jiǎn)而言之:

    在HTML里我們定義了一個(gè)變量q。當(dāng)提交表單時(shí),變量q的值通過GET(method=”get”)附加在URL /search/上。

    處理/search/(search())的視圖通過request.GET來獲取q的值。

需要注意的是在這里明確地判斷q是否包含在request.GET中。就像上面request.META小節(jié)里面提到,對(duì)于用戶提交過來的數(shù)據(jù),甚至是正確的數(shù)據(jù),都需要進(jìn)行過濾。 在這里若沒有進(jìn)行檢測(cè),那么用戶提交一個(gè)空的表單將引發(fā)KeyError異常:

# BAD!def bad_search(request):  # The following line will raise KeyError if 'q' hasn't  # been submitted!  message = 'You searched for: %r' % request.GET['q']  return HttpResponse(message)

查詢字符串參數(shù)

因?yàn)槭褂肎ET方法的數(shù)據(jù)是通過查詢字符串的方式傳遞的(例如/search/?q=django),所以我們可以使用requet.GET來獲取這些數(shù)據(jù)。我們知道在視圖里可以使用request.GET來獲取傳統(tǒng)URL里的查詢字符串(例如hours=3)。

獲取使用POST方法的數(shù)據(jù)與GET的相似,只是使用request.POST代替了request.GET。那么,POST與GET之間有什么不同?當(dāng)我們提交表單僅僅需要獲取數(shù)據(jù)時(shí)就可以用GET; 而當(dāng)我們提交表單時(shí)需要更改服務(wù)器數(shù)據(jù)的狀態(tài),或者說發(fā)送e-mail,或者其他不僅僅是獲取并顯示數(shù)據(jù)的時(shí)候就使用POST。 在這個(gè)搜索書籍的例子里,我們使用GET,因?yàn)檫@個(gè)查詢不會(huì)更改服務(wù)器數(shù)據(jù)的狀態(tài)。 (如果你有興趣了解更多關(guān)于GET和POST的知識(shí),可以參見http://www.w3.org/2001/tag/doc/whenToUseGet.html。)

既然已經(jīng)確認(rèn)用戶所提交的數(shù)據(jù)是有效的,那么接下來就可以從數(shù)據(jù)庫(kù)中查詢這個(gè)有效的數(shù)據(jù)(同樣,在views.py里操作):

from django.http import HttpResponsefrom django.shortcuts import render_to_responsefrom mysite.books.models import Bookdef search(request):  if 'q' in request.GET and request.GET['q']:    q = request.GET['q']    books = Book.objects.filter(title__icontains=q)    return render_to_response('search_results.html',      {'books': books, 'query': q})  else:    return HttpResponse('Please submit a search term.')

讓我們來分析一下上面的代碼:

  •     除了檢查q是否存在于request.GET之外,我們還檢查來reuqest.GET[‘q']的值是否為空。
  •     我們使用Book.objects.filter(title__icontains=q)獲取數(shù)據(jù)庫(kù)中標(biāo)題包含q的書籍。 icontains是一個(gè)查詢關(guān)鍵字。這個(gè)語句可以理解為獲取標(biāo)題里包含q的書籍,不區(qū)分大小寫。
  •     這是實(shí)現(xiàn)書籍查詢的一個(gè)很簡(jiǎn)單的方法。 我們不推薦在一個(gè)包含大量產(chǎn)品的數(shù)據(jù)庫(kù)中使用icontains查詢,因?yàn)槟菚?huì)很慢。 (在真實(shí)的案例中,我們可以使用以某種分類的自定義查詢系統(tǒng)。 在網(wǎng)上搜索“開源 全文搜索”看看是否有好的方法)

    最后,我們給模板傳遞來books,一個(gè)包含Book對(duì)象的列表。 查詢結(jié)果的顯示模板search_results.html如下所示:

<p>You searched for: <strong>{{ query }}</strong></p>{% if books %}  <p>Found {{ books|length }} book{{ books|pluralize }}.</p>  <ul>    {% for book in books %}    <li>{{ book.title }}</li>    {% endfor %}  </ul>{% else %}  <p>No books matched your search criteria.</p>{% endif %}

    注意這里pluralize的使用,這個(gè)過濾器在適當(dāng)?shù)臅r(shí)候會(huì)輸出s(例如找到多本書籍)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 垣曲县| 洛南县| 佛冈县| 青川县| 琼海市| 佛山市| 奎屯市| 晋中市| 合川市| 昭通市| 肥乡县| 嘉禾县| 溆浦县| 米脂县| 怀集县| 建瓯市| 竹山县| 青神县| 宝清县| 邵阳市| 宁陵县| 岱山县| 中山市| 虹口区| 会昌县| 正镶白旗| 泰顺县| 奇台县| 禹州市| 临漳县| 缙云县| 长岛县| 翁牛特旗| 怀集县| 玉门市| 三亚市| 会理县| 磐石市| 林周县| 平阳县| 巴林右旗|