如何在模板中获取表单的外键值?

时间:2015-04-11 22:33:04

标签: django django-models django-forms django-templates django-admin

所以我试图创建一个类似django admin的类似面板,当我的表格设置了查询信息和过滤器时,我试图复制" editable"选项通过创建可在表中编辑的字段。我的问题是让我说我​​有模特:

class model1(model.Models):
  name = CharField(max_length = 20)
  phone = IntegerField(max_length = 20)
  def __unicode__(self):
     return (#I Just return the name and phone number as a string here)

class model2(model.Models):
  name = ForeignKeyFeild(model1)
  team = CharField(max_length = 20)

如果我在视图中设置了这样的modelformset工厂:

qset = model2.objects.all()
fset = modelformset_factory(model2)
form = fset(queryset = qset)

在模板中,如何显示' phone'的价值?来自model1?

当我在模板中渲染表单时:

{% for f in form %}
  {{f.team.value}} # this gives me the value without an input field
  {{f.name.phone.value}} # this however renders nothing and that's what I'm trying to find out
{%endfor%}

另外我如何才能使{{f.name.value}}向我显示unicode字符串而不是实际数值(ID)?

如何将{{f.name.phone}}作为其持有foreign_key节目的表中的信息?

如果没有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

原始模型对象可用作表单的instance属性:

{% for f in form %}
    {{ f.instance.team }}
    {{ f.instance.name.phone }}
{% endfor %}