Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate select option dropdown with database info in django

Tags:

django

I have a django project with a select dropdown. I have typed in the names of players that users can select, but i want to populate the dropdown with the same names but dynamically from the database. How can i go about this?

This is my html so far, not sure how to write the views.py for this, or if i should do a for loop or and if.

<form method="POST">

{% csrf_token %}

   <select id="playerselect" name="pitcher" class="player-dropdown">
    <option value="{{ pitching.id}}">{{ pitching.player_name }}</option>
    <option value="2">Yadiel Lugo</option>
    <option value="3">Cody Reeds</option>
    <option value="4" >Xavier Colon</option>
    <option value="5" >Andy Smith</option>
    <option value="6" >Carson Rex</option>
    <option value="7" >Jalen Jackson</option>
    <option value="8" >Matthew Cobbs</option>
    <option value="9" >Matt Sampson</option>
    <option value="10" >John Harrison</option>
    <option value="11" >Robert Santiago</option>
    <option value="12" >Efrain Zuniga</option>
    <input type="submit" value="Search"/>
    </select> 
like image 558
Joel Orlando Otero Avatar asked Nov 15 '25 07:11

Joel Orlando Otero


1 Answers

In view.py get all the options that you want to see in your HTML

options = yourmodels.objects.filter(foo=bar)

Then pass it in your context dictionary

context = {'options': options, ...}

Then In Your HTML

<select id="playerselect" name="pitcher" class="player-dropdown">
{% for option in options %}
    <option value="{{ option.id}}">{{ option.player_name }}</option>
{% endfor %}
<input type="submit" value="Search"/>
</select>
like image 96
Imran Rahman Avatar answered Nov 17 '25 21:11

Imran Rahman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!