到目前為止我們僅僅是通過視圖和模板來表現數據.在本章,我們將會學習如何通過web表單來獲取數據.Django包含一些表單處理功能,它使在web上收集用戶信息變得簡單.通過Django’s documentation on forms我們知道表單處理功能包含以下:
- 顯示一個HTML表單自動生成的窗體部件(比如一個文本字段或者日期選擇器).
- 用一系列規則檢查提交數據.
- 驗證錯誤的情況下將會重新顯示表單.
- 把提交的表單數據轉化成相關的Python數據類型.
使用Django表單功能最大的好處就是它可以節省你的大量時間和HTML方面的麻煩.這部分我們將會注重如何通過表單讓用戶增加目錄和頁面.
基本流程
頁面和目錄表單
首先,我們需要在rango應用目錄里黃建叫做forms.py文件.盡管這步我們并不需要,我們可以把表單放在models.py里,但是這將會使我們的代碼簡單易懂.
1 創建ModelForm類
在rango的forms.py
模塊里我們將會創建一些繼承自ModelForm
的類.實際上,ModelForm是一個幫助函數,它允許你在一個已經存在的模型里創建Django表單.因為我們定義了兩個模型(Category和Page),我們將會分別為它們創建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 創建和增加目錄視圖
創建CategoryForm類以后,我們需要創建一個新的視圖來展示表單并傳遞數據.在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()視圖增加幾個表單的關鍵功能.首先,檢查HTTP請求方法是GET還是POST.我們根據不同的方法來進行處理 - 例如展示一個表單(如果是GET)或者處理表單數據(如果是POST) -所有表單都是相同URL.add_category()視圖處理以下三種不同情況:
為添加目錄提供一個新的空白表單;
保存用戶提交的數據給模型,并轉向到Rango主頁;
如果發生錯誤,在表單里展示錯誤信息.
3 創建增加目錄模板
讓我們創建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 映射增加目錄視圖
現在我們需要映射add_category()視圖.在模板里我們使用/rango/add_category/URL來提交.所以我們需要修改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 修改主頁內容
作為最后一步,讓我們在首頁里加入鏈接.修改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>
效果圖
.