不工作 {% csrf_token %}

Not working {% csrf_token %}

Django 1.9.5 CSRF 令牌未添加隐藏的表单字段。尝试 render_to_request 与 RequestContext,只是呈现,尝试装饰器 - 没有任何效果,隐藏的输入不显示

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})

你没有通过 RequestContext with 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")