在模板上显示表单

时间:2012-02-25 00:32:35

标签: python django

我有这个型号:

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,但我想要供应商名称。

2 个答案:

答案 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 %}