摘要:Form
url.py
url(r'^FormDemo$', 'app.views.FormDemo', name='FormDemo'),
views.py
def FormDemo(request): assert isinstance(request,HttpRequest) if(request.method=='GET'): #GET form=MyForm() else: form=MyForm(request.POST) #POST if form.is_valid(): name=form.cleaned_data["Name"] #取得 Form 值 bir=form.cleaned_data["Bir"] sex=form.cleaned_data["Sex"] return HttpResponse(name+'驗證完成!!') return render(request,'app/FormDemo.html',{'form':form})
FormDemo.html
<form action='/FormDemo' method='post'>{% csrf_token %}
{% for field in form %}
<div style="padding:2px;float:none;">
{{ field.label_tag }} {{ field }}
</div>
{% endfor %}
<ol>
{% for field in form %}
{% if field.errors|striptags != '' %}
<li style="color:red"><strong>{{ field.label_tag }}{{ field.errors|striptags }} </strong> </li>
{% endif %}
{% endfor %}
</ol>
<input type='submit' value='送出' />
</form>
補充:
FormDemo.html 的 {% csrf_token %} 為 CSRF 跨網站請求偽造攻擊 的處理方式
參考網頁: