CSRF验证失败。请求中止

我尝试建立一个非常简单的网站,在该网站中可以将数据添加到sqlite3数据库中。我有两个文本输入的POST表单。

index.html:

{% if top_list %}

<ul>

<b><pre>Name Total steps</pre></b>

{% for t in top_list %}

<pre>{{t.name}} {{t.total_steps}}</pre>

{% endfor %}

</ul>

{% else %}

<p>No data available.</p>

{% endif %}

<br>

<form action="/steps_count/" method="post">

{% csrf_token %}

Name: <input type="text" name="Name" /><br />

Steps: <input type="text" name="Steps" /><br />

<input type="submit" value="Add" />

</form>

forms.py:

from django import forms

from steps_count.models import Top_List

class Top_List_Form(forms.ModelForm):

class Meta:

model=Top_List

views.py:

# Create your views here.

from django.template import Context, loader

from django.http import HttpResponse

from steps_count.models import Top_List

from steps_count.forms import Top_List_Form

from django.template import RequestContext

from django.shortcuts import get_object_or_404, render_to_response

def index(request):

if request.method == 'POST':

#form = Top_List_Form(request.POST)

print "Do something"

else:

top_list = Top_List.objects.all().order_by('total_steps').reverse()

t = loader.get_template('steps_count/index.html')

c = Context({'top_list': top_list,})

#output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])

return HttpResponse(t.render(c))

但是,当我单击“提交”按钮时,出现403错误:

CSRF verification failed. Request aborted.

我已经包含{% csrf_token %}在index.html中。但是,如果这是一个RequestContext问题,我真的不知道在哪里以及如何使用它。我希望所有事情都在同一页面上发生(index.html)。

回答:

使用自动添加的render快捷方式RequestContext。

from django.http import HttpResponse

from django.shortcuts import get_object_or_404, render

from steps_count.models import Top_List

from steps_count.forms import Top_List_Form

def index(request):

if request.method == 'POST':

#form = Top_List_Form(request.POST)

return HttpResponse("Do something") # methods must return HttpResponse

else:

top_list = Top_List.objects.all().order_by('total_steps').reverse()

#output = ''.join([(t.name+'\t'+str(t.total_steps)+'\n') for t in top_list])

return render(request,'steps_count/index.html',{'top_list': top_list})

以上是 CSRF验证失败。请求中止 的全部内容, 来源链接: utcz.com/qa/434306.html

回到顶部