简体   繁体   中英

How can i enter value into select/option from django model?

this is my first question here.

I've a model that looks like this;

class Fund(models.Model):

    name = models.CharField(max_length=500, null=False, blank=False)
    code = models.CharField(max_length=5, null=False, blank=False)
    management_price = models.CharField(max_length=15, null=True, blank=True)
    performance_price = models.CharField(max_length=15, null=True, blank=True)
    explanation = models.TextField(max_length=1000, null=True, blank=True)

And i want to show all Fund names in a select area in the template here;

<div class="form-group col-md-12">
   <label>Fon*</label>
      <select id="fundIdSelect" class="form-control select2">
         <option value="0">Lütfen Fon Seçiniz</option>
       </select>
</div>

And this my relevant views.py;

def privacy(request):
   fund_list = Fund.objects.all()
   return render(request, 'privacy.html', context={'fund_list': fund_list})

You can iterate the queryset in template. (I am assuming you want names in drop down.)

<div class="form-group col-md-12">
   <label>Fon*</label>
      <select id="fundIdSelect" class="form-control select2">
         {% for i in fund_list %}
         <option value="{{ i.name }}">{{ i.name }}</option>
         {% endfor %}
       </select>
</div>

You suppose to run a for loop in your privacy.html file like this with your div tag:

{% for funds in fund_list  %}
       {{ funds }}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM