简体   繁体   中英

how to delete and objects from the db without refreshing the page?

I have a page that shows every objects in the database, this is handled by an ajax function that gets a JSON file containing every objects in the db and renders out some html code for every object. There's also a classic Django ModelForm that allows the creations of new db's objects, the new objects is instantly loaded with the others.

I want an html button for every objects that deletes it "on the fly", so without redirecting to a Detail Delete template.


$('.remove').on('click', function() {
  $.ajax({
    type:'DELETE'
    url: 'http://127.0.0.1:8000/MyApp/list-api/' + $(this).attr('data-id')
}

When the button is clicked it should send a DELETE request to the url of the detail api of the object. Nothing happens, no new request in the network tab of the browser.

This is my index.html

<body>
    <h2>coffee orders</h2>
    <ul id="orders">

    </ul>

    <h4>Add coffee order</h4>

<form method="POST" action=".">
    {% csrf_token %}
    {{form.as_p}}
    <button id="add-order" type="submit">Add!!!</button>
</form>




    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="{% static 'MyApp/jquery_js.js' %}"></script>

</body>

This is my jquery.js, this function get the api and renders out the infos about the object and a delete button which doens't work.

$(function (){

    var $orders = $('#orders')

    $.ajax({
        type: 'GET',
        url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json',
        success: function(orders) {
            $.each(orders, function(i, order){
                $orders.append('<li>name: '+order.name+', drink: 
                               '+order.drink+'</li>')
                $orders.append("<form method='DELETE'><button data-id=" + 
                               (order.pk)+" class='remove'>X</button>")
            });
        },
        error: function() {
        alert('errore caricamento ordini');
        }
    });
def list_create_view(request):
    form = DrinkModelForm(request.POST or None)
    if form.is_valid():
        print(form.cleaned_data)
        obj = form.save(commit=False)
        obj.user = request.user
        form.save()
        form = DrinkModelForm()
    context = {"form": form}
    return render(request, "MyApp/index.html", context)


class OrderListView(generics.ListCreateAPIView):
    pass
    serializer_class = OrderSerializer

    def get_queryset(self):
        return Order.objects.all()


class OrderDetailView(generics.RetrieveDestroyAPIView):
    pass
    serializer_class = OrderSerializer

    def get_object(self):
        id_ = self.kwargs.get("pk")
        return get_object_or_404(Order, pk=id_)

The X button should delete the objects from the db but nothings happens, I'm new to jquery so any help is really appreciated, thanks.

You should use the OrderDetailView for deletion and remove that pass from the class definition. BTW, you don't need to override the get_object method if you're passing the pk on the URL.

views.py

class OrderDetailView(generics.RetrieveDestroyAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM