When a column of the database is obtained in the background in the django project, how can it be displayed under the option option in the select tag in the html template?

problem description

Sorry, I am a beginner. I encountered a problem when I tried to use django to make a website. I searched the Internet for a long time. I don"t have an answer. I"d like to ask for advice. What you want to achieve is that in the front-end html, the values in the options in the select drop-down box are automatically obtained in the background database.

the environmental background of the problems and what methods you have tried

my idea is that the front end uses javescript fetch API to obtain the data, and then prints it to the option option (the code writing here is not very clear). In the background, I use django"s orm to fetch data from the database (here I have tried two data formats, returning a list or a json format, but the foreground does not seem to be able to get it). I think there is something wrong with the syntax of my loop. And the data format returned by the background is not clear exactly which one to use.

related codes

/ / Please paste the code text below (do not replace the code with pictures)
the code in html:

<script type="text/javascript">
// get select options
fetch("/api/getSelectOption")
    .then(res => res.json())
    .then((responseJson)=>{
        var selectobj=document.getElementById("test");
        for (var i = 0; i <responseJson; iPP)
            selectobj.options.add(new Option(responseJson[i]))
    })

/ the code for obtaining data in the background

def select(request):
   search_name=models.Webtest.objects.values("name")
   select_list=list(search_name)
   return JsonResponse(select_list, safe=False)

what result do you expect? What is the error message actually seen?

I actually see that the data obtained in chrome is like this. Is there a problem with the format of the data I returned? what is the specific writing method for the front desk to get and print
? I am very sorry. I have been in contact with python and js for only 2 weeks. I feel that there are many problems with my writing.

Aug.04,2021

search_name=models.Webtest.objects.values ('name')
search_name is a list with a structure like [{"name": "test1"}, {"name": "test2"}.]
search_name=models.Webtest.objects.values_list ('name', flat=True)
search_name is also a list with a structure like ["test1", "test2",.]

I think what you want is the second kind

Menu