Piero Pajares
Piero Pajares

Reputation: 277

Error when sending delete by ajax - Django Rest framework

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

To remove simply change the state of my attended field, which is a Boolean (true / false) logical deletion. y estas mis 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',),

The recovery of all data is not a problem, it brings me everything I need.

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

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

$('.btn').click(function(){
      $.ajax({
        url: "{%  url 'api-atendido' %}",
        data: {pk:91},
        type: 'DELETE',
        contentType: 'application/json',
        success: function(result) {
          console.log('atendido correctamente');
        },
       });
  });

It shows me the following error: Reverse for 'api-atendido' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['pedido/(?P<pk>\\d+)/$']

error captures: enter image description here

enter image description here

Something missing? or something am I doing wrong?

Upvotes: 1

Views: 975

Answers (1)

Aneesh R S
Aneesh R S

Reputation: 3827

Issue is due to your url name. Your ajax url is {% url 'api-atendido' %}. That url name required a valid pk rather than sending pk as data. ajax url should be {% url 'api-atendido' 'pk' %}, where pk is the primary key of the model Venta.

$('.btn').click(function(){
    $.ajax({
        url: "{%  url 'api-atendido' 91 %}",
        data: {},
        type: 'DELETE',
        contentType: 'application/json',
        success: function(result) {
            console.log('atendido correctamente');
        },
    });
});

If you are calling the ajax call dynamically, then give the exact url instead of its name. Because template rendering is done by server. So all the template tags are converted during the page rendering. To do it dynamically consider the following code.

$('.btn').click(function(){
    var pk = 91; //replace this with the actual id
    $.ajax({
        url: "pedido/"+pk+"/",
        data: {},
        type: 'DELETE',
        contentType: 'application/json',
        success: function(result) {
            console.log('atendido correctamente');
        },
    });
});

Upvotes: 2

Related Questions