在django中如何迭代和填充选定的选项值

时间:2018-06-14 03:13:39

标签: django django-models django-templates

Models.py

from django.db import models

class World(models.Model):
country = models.CharField(max_length=200)
Language = models.CharField(max_length=200)
Populations = models.CharField(max_length=200)

view.py

from django.shortcuts import render
from app_one.models import World

def index(request):
countries = World.objects.order_by('country')
all_countries = {'list_countries':countries}
return render(request,'app_one/index.html',context=all_countries) 

的index.html

{% if list_countries %}
  <select>
    {% for li in list_countries %}
    <option value="{{ li.country }}">{{ li.country }}</option>
    {% endfor %}
  </select>
    <p>"selected country's Language is "{{ li.language }}" </p>
    <p>"selected country's Population is "{{ li.populations }}" </p>
{% else %}
   <p>No suburbs found</p>
  {% endif %}

一旦用户选择了国家/地区,我就无法填充所选国家/地区的语言和人口。

3 个答案:

答案 0 :(得分:4)

您可以在html选项标记的数据属性中设置语言和填充值。

<select class="countries">
    {% for li in list_countries %}
    <option value="{{ li.country }}" data-population="{{ li.Population }}" data-language="{{ li.Language }}">{{ li.country }}</option>
    {% endfor %}
</select>
<p>selected country's Language is <span class='selected-lang'></span></p>
<p>selected country's Population is <span class='selected-popu'></span></p>

然后使用jquery

 $('.countries').change(function(){
    $self = $(this);
    $('.selected-lang').html($self.attr("data-language"));
    $('.selected-popu').html($self.attr("data-population"));
  });

答案 1 :(得分:1)

谢谢Rajat Bulna 这对我有所帮助。

HTML

@Html.TextBoxFor(m => m.YourDate, "{0:yyyy-MM-dd}", new { type = "date" })

Jquery的

<select class="countries">
{% for li in list_countries %}
<option value="{{ li.country }}" data-population="{{ li.Population }}" data-language="{{ li.Language }}">{{ li.country }}</option>
{% endfor %}
</select>
<p>selected country's Language is <span class='selected-lang'></span></p>
<p>selected country's Population is <span class='selected-popu'></span></p>

答案 2 :(得分:0)

你提到的变量&#34; li&#34;它只能在forloop中使用,你不能在forloop之外使用它。扩展你的forloop的范围以使用&#39; li&#39; p标签中的变量