简体   繁体   中英

Not working {% csrf_token %}

Django 1.9.5 CSRF token not adding hidden form field. Trying render_to_request with RequestContext, just render, trying decorator - nothing works, hidden input dont shows

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

You are not passing RequestContext with render_to_response() . Modify the code to something like this:

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

Or you can just use the render shortcut:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM