0

I have a web app, frontend using normal HTML5, backend using Django.

In the frontend page, I have a JavaScript template literal function. Which is supposed to render all the individual value into a selection box of a queryset passed from backend to a bootstrap table.

view.py:

def view_material(request):
     query_results_publisher = Publisher.objects.all()
     return render(request, 'material/index.html', context={'Publisher':query_results_publisher})

publisher is query set: <QuerySet [<Publisher: >, <Publisher: Arkib Negara Malaysia>, <Publisher: DBP>, <Publisher: Edward Elgar>...]

index.html(bootstrap table + javascript template literal function):

 ...
<th class ='publisher' data-field="book.publisher" data-formatter="renderPublisher">Publisher</th>...    


<script>
        var Publisher = "{{ Publisher }}";
        var publisher = '';    
        function renderPublisher(value) {
           return `select style="width: 7em" name="" id="">
                for (publisher in ${Publisher}) {
               <option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}> 
                  publisher</option>}</select>}`
</script>

But my for loop in javascript template literal function is not working, seems like I have some problem with the template literal usage in for loop.

How to correct my function?

django
  • 43
  • 4

1 Answers1

1

You need check value of Publisher before loop it, if it is array, use for-of, if is object, use for-in. But in your case, I saw you print publisher, not it property, so i guest it must be array ( change if im wrong ) . Something like :

var publishers = "{{ Publisher }}"; // no capital for variable' name

function renderPublisher(value) {
var renderString = 'select style="width: 7em" name="" id=""'
for (publisher of publishers) {
    renderString += `
    <option value="eText" ${value === 'eText' ? "selected" : ""}> ${publisher}</option>`

}
renderString += '</select>'
return renderString;

}

Mòe
  • 269
  • 2
  • 7
  • publisher is queryset, I have tried both for-in and for-of, both got the error: possible iteration over unexpected members – django Nov 09 '21 at 03:51
  • I dont know too much about django, but, you need convert queryset to list like this : https://stackoverflow.com/a/53986954/15623535 and make sure type of publishers is array or object, not string with typeof ( use double quote will make it be string " – Mòe Nov 09 '21 at 06:04
  • But still not working after change to list, it shows string instead of selection box – django Nov 09 '21 at 09:01
  • only show some number, did not show the item name. and waning in the script: possible iteration over unexpected members – django Nov 09 '21 at 12:53
  • try remove double quote : var publishers = {{ Publisher }}; Can you show value of Publisher in string ? – Mòe Nov 09 '21 at 14:24