0

I have a little issue and I don't overcome to solve it. I have a list of Django objects generated in my views.py file and I would like to display these variables in my Javascript part.

I get the list in my Javascript code, but each variable are 'undefined'.

In my views.py file, I have :

context['results2'] = SubMethod.objects.values_list('name', flat=True).all()

with this model :

class SubMethod(EdqmTable):
    name = models.CharField(verbose_name=_('name'), max_length=80, unique=True)

    def __str__(self):
        return self.name

Then, in my HTML/JS part :

function get_sub_method_options(keep_cur) {
  var sel_option = $('select#id_method-group').find("option:selected");
  var sel_val = sel_option.val();
  if (!sel_val) {
    $("select#id_method-sub_method").empty();
    var all_sub_methods = "{{ results2 }}";
    console.log(all_sub_methods.name);
      for (var i = 0; i < all_sub_methods.length; i++) {
        $("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods
      }
    return;
  }

  data = {
    'test_method': $('select#id_method-test_method').find("option:selected").val(),
    'group': sel_val
  };
  $.ajax({
    method: "GET",
    url: '{% url 'ajax_method_submethod' %}',
    data: data

  }).done(function (result) {
    reset_select('id_method-sub_method');
    for (var i = 0; i < result['results'].length; i++) {
      if (keep_cur > 0 & keep_cur == result['results'][i].id)
        $("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>');
      else
        $("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>');
    }
    ;
  });
}

As you can see, I pick up my context variable result2 in this part :

if (!sel_val) {
    $("select#id_method-sub_method").empty();
    var all_sub_methods = "{{ results2 }}";
    console.log(all_sub_methods.name);
      for (var i = 0; i < all_sub_methods.length; i++) {
        $("select#id_method-sub_method").append('<option value="' + all_sub_methods[i].id + '">' + all_sub_methods[i].name + '</option>'); //here add list of all submethods
      }
    return;
  }

In my terminal I get :

<QuerySet ['50% cell culture infective dose (CCID50)', 'Acetic acid in synthetic peptides', 'Acid value', 'Adenylate cyclase', ...]>

But in my Javascript part, it displays this :

enter image description here

Do you have any idea why ?

EDIT :

In my django code, count() displays 450

In my JS code : length display 684

In my database : I have 450 elements

1
  • How would you return back the result from view? Commented Nov 26, 2018 at 9:46

1 Answer 1

1

You need to convert your queryset to a list first. JS does not read querysets.

context['results2'] = list(SubMethod.objects.values_list('name', flat=True).all())

and you may want to skip wrapping results2 in quotes on the JS side and ass safe` to prevent escaping characters:

var all_sub_methods = {{ results2|safe }};
Sign up to request clarification or add additional context in comments.

2 Comments

If I add list() it still remains undefined and I get length : 21450. It counts each character ?
I found a solution thanks to your method and some modifications in my code. Thank you very much !

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.