How to implement ajax with django?

1

I try to implement ajax with django and I get the following error in the browser console

500 (INTERNAL SERVER ERROR)

Sometimes on the cmd it returns this error

And in others I only get this where if I run the function but in the same browser in the browser comes the error 500

I have the following html code

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="{{ STATIC_URL }}js/jquery.js"></script>
   <script>
     function recomienda(id){
        var id_evento=id
        $.ajax({
            data: {'id':id_evento},
            url: '/sugerencias-distributivo/',
            type: 'get',
            success: function(data){
                console.log(data);
            }
        });
    }
</script>
</head>
<body>
......
......

    <a href="" onclick="recomienda('{{ Evento.id }}')" class="btn btn-info">recomendar</a>
 </body>
</html>

views.py

from django.core import serializers
from django.http import HttpResponse
from  apps.agenda.models import Evento


class sugerencias(TemplateView):
def get(self,request,*args,**kwargs):

    event = Evento.objects.get(pk=request.GET['id'])
    data = serializers.serialize('json', event,fields=('Fecha','Inicio'))

    return HttpResponse(data, mimetype='application/json')

urls.py

url(r'^sugerencias-distributivo/$', sugerencias.as_view()),
    
asked by Nestor Valero 21.06.2016 в 00:03
source

1 answer

1

I would use the simplejson library:

from django.utils import simplejson
...
json_response = simplejson.dumps({ 'event':event, ... })                                

return HttpResponse(json_response,content_type='application/json')
    
answered by 26.08.2016 в 14:41