0

I have an issue where the value of multiple item didn't reflect at all to my views.py

request.POST.getlist('listitems[]')

Returns when print

[]

selected_items looks like in my ajax when console

enter image description here

ajax

$.ajax({
    type: "POST",
    url: "{% url 'sales-item' %}",
    data:{
       listitems : selected_items, item_size: selected_items.length}

   }).done(function(data){ .........

views.py I want to insert it multiple to database but it seems before that happen when I tried to print the item_list it doesn't work it returs [] Did I miss something?

item_size = request.POST.get('item_size')
item_list = request.POST.getlist('listitems[]')

print(item_list) //doesnt work

for i in item_size:
      out_items = request.POST.getlist('listitems['+i+']')
      print(out_items)

      additems = table1(quantity = out_items[quantity])
      addsales.save()
3
  • you should print request.POST's dictionary data to see what kind of data you are getting Commented May 11, 2023 at 9:18
  • @ruddra what do you mean? I already tried prinitng item_list using request.POST but it didn't reflect it prints like this [] Commented May 11, 2023 at 9:59
  • There could be a lot of things wrong in your code, but we can not tell exactly what or why. Maybe variable name is wrong, or the data is not coming or something else. So you have to debug it. print is one way of debugging. But better is to do it using a proper debugger like pdb. Alternatively, you can check your IDE for debuggers. Commented May 11, 2023 at 10:44

2 Answers 2

0

you can try this.

ajax side to pass data this format.

listitems : selected_items.join(',')

view.py side.

item_list  = request.POST["listitems"]
item_list = item_list.split(",")
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this ,let say I have two data, then I tried to print your code item_list and the result is like this ['[object Object]', '[object Object]']
how can I get the specific value through this? it is possible?
0

You need to prepare it for sending. JSON can help with that:

$(document).ready(function() {
    list = [1,2,3,4]
    $.ajax({
        method: 'POST',
        url: '/food_output',
        contentType:"application/json",
        data: JSON.stringify({'list': list}),
        success: function (data) {
            //this gets called when server returns an OK response
            alert("it worked!");
        },
        error: function (data) {
            alert("it didnt work");
        }
    });
});

its have a lot of references in SO, example: How to send a list from JavaScript to Django views.py?

Sending a list value via ajax to view in Django

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.