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 for the delete I just change the state of my attended field which is a boolean (true/false) a logical delete.
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',),
Recovering all the data is no problem, it brings me everything I need.
via url: url: "{% url 'api-pedido' %}",
GET
But when I want to do the logical deletion from a button (DELETE) :
UDATE I corrected the problem of the url and it is that I had to send the pk 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');
},
});
});
As you can see in the headers, I added the security csrf since django forces me to use it.
Now if it deletes correctly but I only want to delete logical and it is failing in the destroy function showing me the following error:
It is an error in the function since if I remove it, it is working correctly.
Solved: First the parameters are sent like this:
It asks for csrf for django security and in its documentation it says that with jquery it is implemented in this way:
and in my destroy function it was as attended and it was attended queryset = Venta.objects.exclude(attended=True)
This is enough for it to work :) I hope it helps someone.