我正在尝试制作一个页面,用户可以在其中键入他/她的消息并可以保存它。同时该页面还将显示其中的现有消息。
我无法保存消息。此处显示的消息已保存在 DB 中。
单击提交按钮后,会打开一个 Fobidden 页面,显示 CSRF 验证失败。请求中止。
请指导我在哪里做错了。
查看页面编码是:
# # Create your views here.
from django.http import HttpResponse
from home.models import dbmassage
from django.template import Context, loader
def index(request):
#shows messages from the database
home_message = dbmassage.objects.all()
t = loader.get_template('C:/Users/NILESH/Desktop/Django-1.5.1/templates/home/index.html')
c = Context({'home_message': home_message,})
return HttpResponse(t.render(c))
# handle submit message
if request.method == 'POST':
if request.POST['submit_action'] == 'Submit Message':
# attempt to do submit
b = home_message(request.POST)
if b.is_valid():
b.save()
message = 'Message Submitted.'
else:
# validation failed: show submitted values in form
f = submit_b
return HttpResponse(t.render(c))
And the INDEX page coding I did is :
<h1>The Messages</h1>
<h3>Type Your Message:</h3>
<form action='{{ request.path }}' method='POST'>
{% csrf_token %}
<input type="text" maxlength=80 style="width:300px">
<table>
{{ form }}
<tr>
<td colspan=2 align=right>
<h5>Maximum Length = 80</h5><input name="submit_action" type="submit" value="Submit Message">
</td>
</tr>
</table>
</form>
<h3>The Existing Messages:</h3>
{% if home_message %}
<ul>
{% for b in home_message %}
<li>{{ b.massage }}</li>
{% endfor %}
</ul>
{% endif %}
并且 settings.py 代码只是中间件的事情::
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)