HTML Forms
<form action="/login" method="post">
<div>
<label for="username">Username: </label>
<input type="text" id="username" name="username" />
</div>
<div>
<label for="password">Password: </label>
<input type="password" id="password" name="password" />
</div>
<input type="submit" value="Login" />
</form>
GET & POST
- GET:當請求是要從服務(wù)器獲取信息時畔派,使用
GET
- POST:當請求是要修改服務(wù)器的數(shù)據(jù)時(上傳文件铺遂、修改數(shù)據(jù)庫數(shù)據(jù))镊辕,使用
POST
工作過程
-
GET
將提交的數(shù)據(jù)裝換成字符串,以鍵值對的格式放入URL中(明文)瘟则,然后發(fā)送到服務(wù)器 -
POST
將提交的數(shù)據(jù)進行編碼份殿,放入請求體中膜钓,然后發(fā)送到服務(wù)器
適用情形
GET:用于搜索內(nèi)容(搜索的URL可以保存到書簽中,便于分享)
POST:適用于上傳大文件卿嘲、二進制文件(圖片)颂斜、提交敏感信息(密碼)
Django Forms
Django Forms
Forms Class
# myapp/forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
-
label
忽略時,Django 將根據(jù) field name 自動生成拾枣,如your_name
--Your name
-
max_length
有兩個作用:瀏覽器會限制輸入沃疮;Django 會檢驗提交的值的長度
Views
Form
# myapp/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
- 一般盒让,渲染表單和處理表單都集成在同一個視圖中,這樣司蔬,可以重用一些邏輯
-
is.valid()
驗證提交的數(shù)據(jù)- 驗證成功:返回 True 邑茄, 并將結(jié)果轉(zhuǎn)換成對應(yīng)的 Python 類型 并保存在
form.clean_data
中(字典) - 驗證失敗:返回 Flase
- 驗證成功:返回 True 邑茄, 并將結(jié)果轉(zhuǎn)換成對應(yīng)的 Python 類型 并保存在
- 成功處理表單后俊啼,要使用重定向肺缕;避免用戶點擊 “后退” 時,重復(fù)提交數(shù)據(jù)
模板
# myapp/templates/myapp/get_name.html
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
- form 實例對象只會生成 Form Class 定義的 Widgets授帕,自己還是要在模板中添加
<form>
標簽 和{% cstf_token %}
在模板中使用 Django Forms
以下變量都需要自動添加 <form>
, {% csrf_token %}
, <input type="submit" />
{{ form }}
-
{{ form.as_table }}
: 將 label 和 widgets 放在<tr>
標簽中同木,需要自己添加<table>
-
{{ form.as_p }}
:將 label 和 Widgets 放在<p>
中 -
{{ form.as_ul }}
:將 label 和 widgets 放在<li>
,需要自己添加<ul>
手動渲染 Django Forms
-
{{ form.non_field_errors }}
:class="errorlist nonfield"
-
{{ form.subject.errors }}
:class="errorlist"
-
{{ form.subject.label }}
:表示 label 的文字 {{ form.subject.id_for_label }}
{{ form.subject }}
-
{{ form.subject.label_tag }}
:{{ form.subject.id_for_label }}
+{{ form.subject }}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}