【问题标题】:Have {% csrf_token %} tag in template but no csrfmiddlewaretoken hidden value模板中有 {% csrf_token %} 标记但没有 csrfmiddlewaretoken 隐藏值
【发布时间】:2015-09-01 02:52:09
【问题描述】:

我在 Django 中使用 django.contrib.cmets,版本是 1.6.1 然后我有一个这样的表格,

{% get_comment_form for mbean as form %}
<table>
  <form action="{% comment_form_target %}" method="post" class="aaa">{% csrf_token %}
    {{ form }}
    <tr>
      <td colspan="2">
        <input type="submit" name="submit" value="Post">
        <input type="submit" name="preview" value="Preview">
      </td>
    </tr>
  </form>
</table>

但是当我在 HTML 中检查我的页面源时,我在我的源中找不到&lt;input type='hidden' name='csrfmiddlewaretoken' value='uiwp7YkGi374HwnZqMRbCUmzyH38jDPI' /&gt;,并且有

CSRF 验证失败。请求中止

错误。

我也在这个模板的其他形式中使用了{% csrf_token %},但仍然没有“csrfmiddlewaretoken”。

  1. 没有“csrfmiddlewaretoken”是我有“CSRF”的原因 验证失败。请求中止”错误?

  2. 谁能帮忙看看我的模板出了什么问题?

【问题讨论】:

  • 你的模板很好。问题出在您的设置或您的视图中。可以发一下查看代码吗?
  • 这是我原来的 return render_to_response('suborder.html', RequestContext(request, locals())),然后我按照 Deshraj 的帮助更改为 return render_to_response('suborder.html', RequestContext(request, locals())),它现在可以工作了。也谢谢你,@spectras !!

标签: python django django-models


【解决方案1】:

要在模板中使用 {% csrf_token %},您需要在渲染模板时将 RequestContext 实例传递给模板,然后就可以了。然后您可以使用 csrf_token 并且它也将在源代码中可见。

在渲染模板时发送上下文实例的示例代码 sn-p:

from django.template import RequestContext

def home(request):
    return render_to_response('index.html', context_instance=RequestContext(request))

【讨论】:

    猜你喜欢
    • 2015-05-23
    • 2012-10-14
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 2015-10-16
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多