Error sending delete by ajax - Django Rest framework

0

I have 2 serializers:

class DetalleSerializer(serializers.ModelSerializer):
    producto = serializers.CharField(source='producto.nombre')
    class Meta:
        model = DetalleVenta
        fields = ('cantidad','producto')

class PedidoSerializer(serializers.ModelSerializer):
    detalleventa = DetalleSerializer(many=True, read_only=True)
    class Meta:
        model = Venta
        fields = ('id','cliente','descripcion','detalleventa','atendido')

and my viewset :

class PedidoViewSet(viewsets.ModelViewSet):
    queryset = Venta.objects.exclude(atendido=True)
    serializer_class = PedidoSerializer

    def destroy(self, request, pk=None):
        try:
            queryset = Venta.objects.exclude(atendito=True)
            object = get_object_or_404(queryset, pk=pk)
            object.atendido = True
            object.save(update_fields=['atendido'])
            return Response({"status": True, "results": "Pedido atendido correctamente"})
        except NotFound as err:
            return Response({"status": False, "error_description": err.detail})

In which to remove simply change the state of my attended field which is a Boolean (true / false) logical deletion.

and these are my 2 urls :

url(r'^pedido/$',PedidoViewSet.as_view({'get': 'list', 'post': 'create'}),name='api-pedido',),
url(r'^pedido/(?P<pk>\d+)/$',PedidoViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}),
        name='api-atendido',),

Retrieving all the data is no problem, it brings me everything I need.

through the url: url: "{% url 'api-pedido' %}", GET

But when I want to do the logical deletion from a (DELETE) button:

UDATE I corrected the problem of the url and it is that I had to send it in this way the pk :

$('.btn').click(function(){
   $.ajax({
      url: "{%  url 'api-atendido' pk=85 %}",
      headers: { "X-CSRFToken": getCookie("csrftoken") },
      type: 'DELETE',
      contentType: 'application/json',
      success: function(result) {
         console.log('atendido correctamente');
      },
    });
 });

As you can see in the header add the security csrf since django forces me to use it.

Now if you delete it correctly but I just want logical removal and it is failing in the destroy function, showing me the following error:

It's an error in the function because if I remove it, it works correctly.

    
asked by Piero Pajares 04.04.2018 в 02:48
source

1 answer

0

Solved: First the parameters are sent in this way:

$('.btn').click(function(){
   $.ajax({
      url: "{%  url 'api-atendido' pk=85 %}",
      headers: { "X-CSRFToken": getCookie("csrftoken") },
      type: 'DELETE',
      contentType: 'application/json',
      success: function(result) {
         console.log('atendido correctamente');
      },
    });
 });

Requests csrf for security django and in its documentation says that with jquery it is implemented in this way:

// using jQuery
            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;
            }

and in my function of destroy I was treated and treated queryset = Venta.objects.exclude (attended = True)

This is enough to make it work :) I hope you serve someone.

    
answered by 04.04.2018 / 06:51
source