403 Error prohibido al realizar una solicitud de publicación ajax en el marco de Django

Estoy tratando de integrar jquery en una aplicación web que estoy haciendo con el framework Django. Sin embargo, estoy teniendo dificultades para hacer un sencilloajax llamar al trabajo El archivo de mi plantilla que contiene el formulario html y javascript para manejar la llamada ajax se ve así:

<script type="text/javascript">
$(document).ready(function() {
$( "#target" ).submit(function() {
console.log('Form was submitted');
$.ajax({
        type: "POST",
        url: "/hello/",  // or just url: "/my-url/path/"
        data: {
            query: $( "#query" ).val()   
        },
        success: function(data) {
            console.log(data);
        }
    });
return false;
  });   
  })
</script>
<form id="target" action="." method="post">{% csrf_token %}
 <input id= "query" type="text" value="Hello there">
 <input type="submit" value="Search Recent Tweets">
</form>

Miviews.py que se supone que maneja la llamada ajax se ve así:

 from django.core.context_processors import csrf
 from django.shortcuts import render_to_response
 from django.template.loader import get_template
 from django.template import Context,RequestContext
 from django.views.decorators.csrf import ensure_csrf_cookie
 from django.http import HttpResponse

 # access resource
 def hello(request):
  c = {}
  c.update(csrf(request))
  if request.is_ajax():
        t = get_template('template.html')
        #html = t.render(Context({'result': 'hello world'}))
        con = RequestContext(request, {'result': 'hello world'})
        return render_to_response('template.html', c, con)
  else:
        return HttpResponse('Not working!') 

He intentado seguir la documentación oficial delProtección de falsificación de solicitudes entre sitios y también examinó varias preguntas de stackoverflow que abordan un problema similar. He incluido el{% csrf_token %} en mihtml plantilla de archivo, pero todavía no parece estar funcionando. Recibo un error en la consola que sugiere que la llamada ajax falló:

POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)   

Como paso elresult variable junto con mi respuesta http y hacer que la llamada ajax funcione sin problemas? Cualquier ayuda es muy apreciada.

Edit-1

Supuestamente no estaba pasando elcsrf token junto con mi solicitud de publicación. ASÍ, según la documentación, agregué el siguiente código a mi plantilla javascript:

function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
        var cookie = jQuery.trim(cookies[i]);
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');
console.log(csrftoken);

//Ajax call
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

Cuando actualizo la página HTML de la plantilla en el navegador, obtengonull en la consola, lo que sugiere que la cookie no está configurada o no está definida. ¿Qué me estoy perdiendo?

Respuestas a la pregunta(9)

Su respuesta a la pregunta