到目前為止我們僅僅是通過(guò)視圖和模板來(lái)表現(xiàn)數(shù)據(jù).在本章,我們將會(huì)學(xué)習(xí)如何通過(guò)web表單來(lái)獲取數(shù)據(jù).Django包含一些表單處理功能,它使在web上收集用戶信息變得簡(jiǎn)單.通過(guò)Django’s documentation on forms我們知道表單處理功能包含以下:
- 顯示一個(gè)HTML表單自動(dòng)生成的窗體部件(比如一個(gè)文本字段或者日期選擇器).
- 用一系列規(guī)則檢查提交數(shù)據(jù).
- 驗(yàn)證錯(cuò)誤的情況下將會(huì)重新顯示表單.
- 把提交的表單數(shù)據(jù)轉(zhuǎn)化成相關(guān)的Python數(shù)據(jù)類型.
使用Django表單功能最大的好處就是它可以節(jié)省你的大量時(shí)間和HTML方面的麻煩.這部分我們將會(huì)注重如何通過(guò)表單讓用戶增加目錄和頁(yè)面.
基本流程
頁(yè)面和目錄表單
首先,我們需要在rango應(yīng)用目錄里黃建叫做forms.py文件.盡管這步我們并不需要,我們可以把表單放在models.py里,但是這將會(huì)使我們的代碼簡(jiǎn)單易懂.
1 創(chuàng)建ModelForm類
在rango的forms.py
模塊里我們將會(huì)創(chuàng)建一些繼承自ModelForm
的類.實(shí)際上,ModelForm是一個(gè)幫助函數(shù),它允許你在一個(gè)已經(jīng)存在的模型里創(chuàng)建Django表單.因?yàn)槲覀兌x了兩個(gè)模型(Category和Page),我們將會(huì)分別為它們創(chuàng)建ModelForms.
在rango/forms.py
添加下面代碼:
from django import forms
from rango.models import Page, Category
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="Please enter the category name.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
# An inline class to provide additional information on the form.
class Meta:
# Provide an association between the ModelForm and a model
model = Category
fields = ('name',)
class PageForm(forms.ModelForm):
title = forms.CharField(max_length=128, help_text="Please enter the title of the page.")
url = forms.URLField(max_length=200, help_text="Please enter the URL of the page.")
views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
class Meta:
# Provide an association between the ModelForm and a model
model = Page
# What fields do we want to include in our form?
# This way we don't need every field in the model present.
# Some fields may allow NULL values, so we may not want to include them...
# Here, we are hiding the foreign key.
# we can either exclude the category field from the form,
exclude = ('category',)
#or specify the fields to include (i.e. not include the category field)
#fields = ('title', 'url', 'views')
2 創(chuàng)建和增加目錄視圖
創(chuàng)建CategoryForm類以后,我們需要?jiǎng)?chuàng)建一個(gè)新的視圖來(lái)展示表單并傳遞數(shù)據(jù).在rango/views.py中增加如下代碼.
from rango.forms import CategoryForm
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
form = CategoryForm(request.POST)
# Have we been provided with a valid form?
if form.is_valid():
# Save the new category to the database.
form.save(commit=True)
# Now call the index() view.
# The user will be shown the homepage.
return index(request)
else:
# The supplied form contained errors - just print them to the terminal.
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = CategoryForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
return render(request, 'rango/add_category.html', {'form': form})
新的add_category()視圖增加幾個(gè)表單的關(guān)鍵功能.首先,檢查HTTP請(qǐng)求方法是GET還是POST.我們根據(jù)不同的方法來(lái)進(jìn)行處理 - 例如展示一個(gè)表單(如果是GET)或者處理表單數(shù)據(jù)(如果是POST) -所有表單都是相同URL.add_category()視圖處理以下三種不同情況:
為添加目錄提供一個(gè)新的空白表單;
保存用戶提交的數(shù)據(jù)給模型,并轉(zhuǎn)向到Rango主頁(yè);
如果發(fā)生錯(cuò)誤,在表單里展示錯(cuò)誤信息.
3 創(chuàng)建增加目錄模板
讓我們創(chuàng)建templates/rango/add_category.html文件.
<!DOCTYPE html>
<html>
<head>
<title>Rango</title>
</head>
<body>
<h1>Add a Category</h1>
<form id="category_form" method="post" action="/rango/add_category/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Category" />
</form>
</body>
</html>
4 映射增加目錄視圖
現(xiàn)在我們需要映射add_category()視圖.在模板里我們使用/rango/add_category/URL來(lái)提交.所以我們需要修改rango/urls.py的urlpattterns.
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^add_category/$', views.add_category, name='add_category'), # NEW MAPPING!
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),)
5 修改主頁(yè)內(nèi)容
作為最后一步,讓我們?cè)谑醉?yè)里加入鏈接.修改rango/index.html文件,在</body>前添加如下代碼.
<a href="/rango/add_category/">Add a New Category</a><br />
6. demo
add_page.htnl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rango - Add Page</title>
</head>
<body>
{% if category %}
<h1>Add a Page to {{ category.name }}</h1>
<form id="page_form" method="post" action="/rango/category/{{ category.slug }}/add_page/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Add Page">
</form>
{% else %}
The specified category does not exist!
{% endif %}
</body>
</html>
效果圖
.