Django 1.2.4 CSRF验证失败 [英] Django 1.2.4 CSRF verification failed

查看:156
本文介绍了Django 1.2.4 CSRF验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行POST表单时,Django 1.2一直在给我这个CSRF验证错误。我认为我已经完成了Django 1.2文档中提到的所有事情,即


  1. 确保MIDDLEWARE_CLASSES包含在'django.middleware.csrf.CsrfViewMiddleware'


  2. 确保{%csrf_token%}

     < form action =/ words / new /method =post> 
    {%csrf_token%}
    {{form.as_p}}
    < input type =submitvalue =Enter/>
    < / form>


  3. 在我的回复中使用RequestContext

      def create(request):
    if request.method =='POST':
    form = DefinitionForm(request.POST)
    如果表单。 is_valid():
    form.save()
    c = {}
    返回render_to_response('dict / thanks.html',c,
    context_instance = RequestContext(request))
    else =
    form = DefinitionForm()
    返回render_to_response('dict / create_definition.html',{
    'form':form,
    })


请注意,GET操作适用于此功能。所以我想我正在使用render_to_response权限。



我甚至试图扔在@csrf_protect装饰器,甚至似乎没有工作。我不在意,我要用自己的笔记本电脑cho。自己。



你们可以想到什么?



谢谢!

解决方案

你没有关注#3。必须使用 RequestContext 与呈现表单的模板一起使用。感谢页面不需要。

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

请注意,您应该使用 PRG模式,而不是直接提交感谢页面。 / p>

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!

解决方案

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.

这篇关于Django 1.2.4 CSRF验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆