Python系列视频教程: Django【13讲】第13讲 表单使用
python %django_home%\bin\django-admin.py startproject csvt07
python %django_home%\bin\django-admin.py startapp blog
setting.py
。。。。。。
urls.py
url(r'^blog/register/$', 'blog.views.register'),
blog\views.py
from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponse
# Create your views here.
class UserForm(forms.Form):
name=forms.CharField()
def register(req):
if req.method == 'POST':
form = UserForm(req.POST)
if form.is_valid():
print form.cleaned_data
return HttpResponse('ok')
else:
form = UserForm()
return render_to_response('register.html',{'form':form})
blog\templates\register.html
<body>
<form method="post">
{{form}}
<input type="submit" value="ok"/>
</form>
</body>
http://127.0.0.1:8000/blog/register/
Name:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrec
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
- Your browser is accepting cookies.
- The view function uses
RequestContext
for the template, instead ofContext
. - In the template, there is a
{% csrf_token %}
template tag inside each POST form that targets an internal URL. - If you are not using
CsrfViewMiddleware
, then you must usecsrf_protect
on any views that use thecsrf_token
template tag, as well as those that accept the POST data.
我们可以修改settings.py
注释掉csrf
重新启动服务器,然后就返回ok
看看服务器打印:
[05/Feb/2014 13:43:18] "GET /blog/register/ HTTP/1.1" 200 510
{'name': u'f'}
[05/Feb/2014 13:43:20] "POST /blog/register/ HTTP/1.1" 200 2
这里面的打印就是下面语句的作用:
print form.cleaned_data
另外,如果什么都不输入,就提交表单,会自动提示错误。