Remove Session Data Dictionary with ajax in Django

Asked

Viewed 82 times

2

I have an array with a data dictionary in my Session and would like to remove according to the row the user is going to click on a table where these values are displayed.

My view:

def deletar_servico_ou_item_selecionado(request):

    if request.is_ajax:
        linhaClicada = request.POST.get('item')
        lista = request.session['ord-serv']
        del lista[linhaClicada - 1]
        request.session['ord-serv'] = lista

    return HttpResponse("/")

My JS:

var linhaClicada = $(this).parent().index();
$.ajax({
    url: "/atendimento/deletar-servico-ou-item-selecionado/",
    type: "POST",
    data: {item: linhaClicada},
    success: function(response) {
        console.log("Success");
    },
    error: function(response) {
        console.log("Error");
    }
});

It seems my value doesn’t reach Django and I don’t know if I should use the type: "DELETE" in that case.

1 answer

1


To remove the item from your list from the index, you can use list.pop, for example:

lista = [{"0":"0"},{"1":"1"},{"2":"2"},{"3":"3"},{"4":"4"},{"5":"5"}]
lista.pop(1)
# {'1': '1'}
lista
# [{'0': '0'}, {'2': '2'}, {'3': '3'}, {'4': '4'},{"5":"5"}]

If you do not need csrf_token in your request, you can include at the beginning of your function the @csrf_exempt, and import it from django.views.decorators.csrf import csrf_exempt. If yes, you must pass along with the data you are giving post. date : {csrfmiddlewaretoken: '{{ csrf_token }}'}

  • Thank you for your answer, but my problem is linhaClicada does not reach AJAX.

  • Place a dataType: "json", below its date: {item: Clicate}. Also check that when calling ajax, still in the script, there is some value for binary

  • You should also look at your log console to see if there is an error in the script and if the view is being called correctly. You can debug what is coming in your post with pdb. import pdb; pdb.set_trace() https://mike.tig.as/blog/2010/09/14/pdb/

  • And put your dictionary in quotes. date: {"item": lineClicate}, :)

  • The following message is coming: list indices must be integers, not NoneType, but my lineClicate has a value.

  • In your view, try to get the data with: data = request.POST['data']. You have to see what’s coming in your view and how it’s coming in. You must be sending the information to the view but not getting it right.

  • That’s probably it, now you’re showing the following error: MultiValueDictKeyError at /atendimento/deletar-servico-ou-item-selecionado/
"'item'"

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.