Python系列视频教程: Django【13讲】第13讲 表单使用

31 篇文章 0 订阅
23 篇文章 0 订阅

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 of Context.
  • 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 use csrf_protect on any views that use the csrf_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

 

另外,如果什么都不输入,就提交表单,会自动提示错误。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值