显示 OneToOneField 的组合框

Displaying a combobox for a OneToOneField

我想显示一个带有 OneToOneField:

的组合框

models.py:

class Aliment(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    type_aliment_id = models.OneToOneField(type_aliment)
    mesurande_id = models.OneToOneField(mesurande)
    calories = models.IntegerField(default=0)
    proteines = models.IntegerField(default=0)

class type_aliment(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

forms.py:

class AlimentForm(ModelForm):
    class Meta:
        model=Aliment
        field = ('name','type_aliment_id','mesurande_id','calories','proteines')

views.py:

def add_aliment(request):
  add_aliment = AlimentForm()
  return render_to_response("add_aliment.html",
                          {'form_aliment':add_aliment,},RequestContext(request))

我想显示 "Aliment" 的所有列,但对于 "type_aliment_id" 我想有一个包含所有名称的组合框 "type_aliment" : 它不起作用,但我不知道为什么 :

<form id="myForm" action="" method="post">{% csrf_token %}
  <select name="select_type" id="id_select_type">
    {% for type_aliment in form_aliment.type_aliment_id %}
    <option value="{{ type_aliment.id }}">{{ type_aliment.name}}</option>
    {% endfor %}
</select>

您不需要手动构建组合框。它将由 Django 自动创建。只需使用

<form id="myForm" action="" method="post">
    {% csrf_token %}
    {{ form_aliment }}
    <button type="submit">Submit</button>
</select>

作为模板的基础。

您还必须在 class 中实施 __unicode__ 方法才能在组合框中看到他们的名字:

class type_aliment(models.Model):
    ...
    def __unicode__(self):
        return self.name

PS:您的命名约定令人困惑。尝试坚持 Python/Django 标准。 class 名称使用 CamelCase;例如,而不是

class type_aliment(...)

使用

class TypeAliment(...)

并且不要在您的字段名称中添加 _id 后缀。而不是

type_aliment_id = models.OneToOneField(type_aliment)

使用

type_aliment = models.OneToOneField(TypeAliment)

它将帮助其他编码人员(如 Stack Overflow 上的此处)更轻松地阅读您的代码。