不工作{%csrf_token%}

时间:2016-04-10 19:00:50

标签: python django csrf

Django 1.9.5 CSRF令牌不添加隐藏表单字段。尝试使用RequestContext渲染render_to_request,只需渲染,尝试装饰器 - 没有任何效果,隐藏输入不显示

home.html

<script>
$(document).ready(function() {
    $("#encrypt").click(function () {
        var postData = {
            text: $("#input-box").val(),
            rotate: $("#rotate").val()
        };
        $.post('/encrypt', postData, function (out){
            alert(out)
        });
    });
});
  </script>
<form name="ciepher" method="POST" action="">
          {% csrf_token %}
 <!-- form code-->
</form>

views.py

from django.shortcuts import render_to_response, render
from django.template import RequestContext
from caesar import models

def home(request):
    return render_to_response("home.html")

def encrypt(request):
    input_text = request.POST["text"]
    rotate = request.POST["rotate"]
    output_text = models.encode(input_text, rotate)
    frequency = models.get_frequency(input_text)
    #return render_to_response("home.html", {'input_text': input_text, 'rotate': rotate, 'output_text': output_text, 'frequency': frequency}, context_instance = RequestContext(request))
    return render(request,"home.html", {'input_text': input_text, 'rotate': rotate, 'output_text': output_text, 'frequency': frequency})

1 个答案:

答案 0 :(得分:2)

您没有通过RequestContext传递render_to_response()。将代码修改为以下内容:

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

或者您可以使用render快捷方式:

def home(request):
    return render(request, "home.html")