Django 1.2.4 CSRF verification failed

柔情痞子 提交于 2019-12-09 10:32:40

问题


Django 1.2 is consistently giving me this CSRF verification error when I perform a POST form. I "think" I've done all the things asked in the Django 1.2 docs, namely,

  1. Ensure MIDDLEWARE_CLASSES is included with 'django.middleware.csrf.CsrfViewMiddleware'

  2. Ensure the {% csrf_token %}

    <form action="/words/new/" method="post">
    {% csrf_token %}
    {{ form.as_p }}
        <input type="submit" value="Enter" />
    </form>
    
  3. Use RequestContext in my response

    def create(request):
        if request.method == 'POST':
            form = DefinitionForm(request.POST)
            if form.is_valid():
                form.save()
            c = {}
            return render_to_response('dict/thanks.html',c, 
                                        context_instance=RequestContext(request))
        else:
            form = DefinitionForm()
        return render_to_response('dict/create_definition.html', {
            'form' : form,
        })
    

Note that the GET action works in this function. So I think I'm using render_to_response right.

I've even tried to throw in the @csrf_protect decorator and even that didn't seem to work. I'm out of ideas and I'm about to choke myself with my laptop.

Any thing you guys can think of?

Thanks!


回答1:


You're not following #3. The RequestContext must be used with the rendering of the template that shows the form. It's not necessary for the thanks page.

return render_to_response('dict/create_definition.html', {
    'form' : form,
}, context_instance=RequestContext(request))

And as a side note, you should use the PRG pattern instead of rendering the thanks page directly.



来源:https://stackoverflow.com/questions/4775034/django-1-2-4-csrf-verification-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!