在创建一个站点联系表单的时候,表单如下:
运行django,点击提交之后,出现以下错误:
出现这种情况的原因,在django开启了debug功能后已经被列出了,其中1)、3)以及4)操作都已经做了,但是还是出现了错误,查看django1.4官方文档,在视图views.py中还需要进行相应的调整,也就是渲染模板时,不能简单的使用Context,而应该使用RequestContext来代替它,调整之后视图代码如下:
也就是修改21-22的代码,把原来的两行代码(如下)
点击(此处)折叠或打开
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
- "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <title>联系我们</title>
- </head>
- <body>
- <h1>联系我们</h1>
- {% if errors %}
- <ul>
- {% for error in errors %}
- <li>{{ error }}</li>
- {% endfor %}
- </ul>
- {% endif %}
- <form action="/contact/" method="post">{% csrf_token %}
- <p>主题: <input type="text" name="subject"></p>
- <p>邮箱地址 (可选): <input type="text" name="email"></p>
- <p>信息: <textarea name="message" rows="10" cols="50"></textarea></p>
- <input type="submit" value="提交">
- </form>
-
- </body>
- </html>
点击(此处)折叠或打开
- Forbidden (403)
- CSRF verification failed. Request aborted.
- Help
- Reason given for failure:
- CSRF token missing or incorrect.
- 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:
- 1)Your browser is accepting cookies.
- 2)The view function uses RequestContext for the template, instead of Context.
- 3)In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
- 4)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.
点击(此处)折叠或打开
- from django.shortcuts import render_to_response
- from django.http import HttpResponseRedirect
- from django.core.mail import send_mail
- from django.template import RequestContext
-
- def contact(request):
- errors = []
-
- if request.method == 'POST':
- if not request.POST.get('subject', ''):
- errors.append('Enter a subject')
- if not request.POST.get('message', ''):
- errors.append('Enter a message')
- if request.POST.get('email') and '@' not in request.POST['email']:
- errors.append('Enter a valid e-mail address')
- if not errors:
- send_mail(request.POST['subject'], request.POST['message'],
- request.POST.get('email', 'zqlongqiang@gmail.com'),['long_xitianxia@126.com',])
- return HttpResponseRedirect('thanks')
-
- return render_to_response('contact_form.html',
- RequestContext(request,{'errors': errors}))
- return render_to_response('contact_form.html',
- {'errors': errors})#默认为Context
修改成:
- return render_to_response('contact_form.html',
- RequestContext(request,{'errors': errors}))
这样问题就得以解决了!
注: 仅能解决不适用forms。py 自校验程序,加入forms.py 以后报错。
--- 新的一天,重启应用测试发现好了,真奇特啊!