我有这个型号:
class Supplier(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return u"%s" % self.name
class SupplierOrder(models.Model):
supplier = models.ForeignKey(Supplier)
numero_invoice = models.CharField(max_length=50)
我有这样的表格:
class SupplierOrderForm(forms.ModelForm):
class Meta:
model = SupplierOrder
将供应商订单表单传递给模板,我有这个代码:
<table>
{% for f in forms %}
{% for field in f.visible_fields %}
<tr>
<td>{{ field.label_tag }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
{% endfor %}
问题是供应商显示供应商ID,但我想要供应商名称。
答案 0 :(得分:1)
将__unicode__
方法添加到您的模型中:
class Supplier(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return u"%s" % self.name
答案 1 :(得分:0)
这个forloop的field
值是BoundField的一个实例:
{% for field in f.visible_fields %}
您可以获取BoundField实例的值:
boundfield.field.to_python(boundfield.value())
所以你可以make a trivial template filter:
from django import template
register = template.Library()
@register.filter
def to_python(boundfield):
return boundfield.field.to_python(boundfield.value())
并在模板中使用它:
{% load your_template_tags %}
{% for field in form.visible_fields %}
<tr>
<td>{{ field.label_tag }}</td>
<td>{{ field|to_python }}</td>
</tr>
{% endfor %}