Essex
Essex

Reputation: 6128

Get Django variable in Javascript : undefined value

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

Upvotes: 0

Views: 873

Answers (1)

Sina Khelil
Sina Khelil

Reputation: 1991

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 }};

Upvotes: 1

Related Questions