Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - CSRF verification failed. Request aborted

I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input.

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+''+str(t.total_steps)+'
') for t in top_list])
    return HttpResponse(t.render(c))

However, when I click the "submit" button, I get the 403 error:

CSRF verification failed. Request aborted.

I have included {% csrf_token %} in index.html. However, if it is a RequestContext problem, I really have NO idea on where and how to use it. I want everything to happen on the same page (index.html).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may have missed adding the following to your form:

{% csrf_token %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...