1

I am trying to display list of names from a django queryset using , Here is my code

def vfunc(request):
    context={}
    bats = Bat.objects.all().order_by('-id')
    context['bats'] = bats
    [each.batname for each in bats] # Gives all the batnames. 
    return render(request, 'bat.html', context)

I want to display batnames on template

$(function() {
//This works when I hardcode the values
    var batData =  [{
            "bat":"batname1", //hardcoded & displayed in 1st row
        },  {
            "bat":"batname2", //hardcoded & displayed in 2nd row
        }];
        $("#CleanDatasNames").dxDataGrid({
            dataSource: batData,
            ...
            ...
            }

I am tried something like var batData = [{"bat":"{{bats|join:', ' }}"] but it is displaying obj1,obj2 in same row,I also tried to loop through but failed , any help will appreciated.

1 Answer 1

3

This way you can work with js:

$(function() {
//This works when I hardcode the values
    var batData =  [
{% for bat in bats %}  
{
            "bat":"{{bat}}", 
}
{% if forloop.counter != bats|length %} // dynamically checking for last element
    , 
{% endif %}
{% endfor %}
];
        $("#CleanDatasNames").dxDataGrid({
            dataSource: batData,
            ...
            ...
            }
Sign up to request clarification or add additional context in comments.

3 Comments

This is a great help, thanks a lot @Jafoor
1 qoubt, please explaing the if condition forloop.counter , is it necessary?
generally, we don't use , the last element. Javascript may not bother with , if you use it or not. But for clean and perfect code you can use it.

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.