【问题标题】:Dropdown List Foreign Key Django [duplicate]下拉列表外键Django [重复]
【发布时间】:2019-05-15 05:10:56
【问题描述】:

美好的一天。我有事要问。

我有学生模型,在那个学生模型中我有外键地址,我要问的是我想从单独的下拉列表中的外键地址创建一个下拉列表,除了 zip_code,如下图所示:

Student(models.Model):
    ...
    ....
    Address = models.Foreignkey(Address)

Address(models.Model):
    zip_code = models.CharField(...)
    city = model.Charfield(..)
    province= model.Charfield(..)
    country= model.Charfield(..)

谢谢。check here the expected output

【问题讨论】:

  • 地址模型中有哪些字段?添加地址模型也用于清除
  • 这是我完整的地址模型。类地址(models.Model): country = models.Charfield(max_length=200) Province = models.Charfield(max_length=200) zip = models.Charfield(null=True, blank=True, max_length=7, validators=[RegexValidator (r'^d(1,10}$')]) city = models.Charfield(max_length=200)

标签: python django


【解决方案1】:

在views.py中循环遍历学生对象如下:

<select id="city">
{% for address in object.address_set.all %}
<option value={{address.city}}>{{address.city}}</option>
{% endfor %}
</select>

<select id="province">
{% for address in object.address_set.all %}
<option value={{address.province}}>{{address.province}}</option>
{% endfor %}
</select>

<select id="country">
{% for address in object.address_set.all %}
<option value={{address.country}}>{{address.country}}</option>
{% endfor %}
</select>

【讨论】:

  • 我想知道我在views.py中要做什么
  • 只返回学生对象
猜你喜欢
  • 2017-04-06
  • 1970-01-01
  • 2015-05-25
  • 2014-06-10
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
相关资源
最近更新 更多