gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:22:48 25 4
gpt4 key购买 nike

模型.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)

查看.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 %}

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

最佳答案

您可以在 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"));
});

关于django - 在 django 中如何迭代和填充选定的选项值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50849077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com