Django ModelForm未显示在模板中

时间:2012-05-16 19:58:59

标签: django django-templates django-forms

我在models.py文件的底部有一些ModelForms。一些模型正在工作(即它们正确地显示在模板中)。

以下是其中两项有效:

class Account_Balance_Form(ModelForm):
    class Meta:
        model = Account_Balance
        fields = ('date','balance')

class Asset_Form(ModelForm):
    class Meta:
        model = Asset
        exclude = ('account','id')

其他人不起作用。甚至使用相同的视图(将不同的ModelForm传递给同一个模板)。这些是2不起作用:

class Allocation_Form(ModelForm):
    class Meta:
        model = Allocation

class Deduction_Form(ModelForm):
    class Meta:
        model = Deduction

不确定我做错了什么...我试图运行syncdb,但这没有帮助。此外,看起来表单对象正好被创建:

allocation_form <forecast.models.Allocation_Form object at 0x90f15ac>

他们只是没有被展示......有什么想法吗?

===================

仅供参考,样本视图有效:

def view_allocation(request):
    form = Asset_Form()
    return render_to_response('alloc.html',
                                {'form': form})

不起作用:

def view_allocation(request):
    form = Allocation_Form()
    return render_to_response('alloc.html',
                                {'form': form})

示例模板:

<html>
<body>
{{ form.as_p }}
</body>
</html>

按要求:

class Allocation(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=40)
    account = models.ForeignKey(Account)
    amount = models.DecimalField(max_digits=20,decimal_places=2)
    percent = models.DecimalField(max_digits=10,decimal_places=10)
    allocation_group = models.IntegerField(max_length=11)
    def __unicode__(self):
        return self.name


class Deduction(models.Model):
    iei = models.ForeignKey(Inc_Exp_Item, null=True, blank=True)
    name = models.CharField(max_length=40)
    amount = models.DecimalField(max_digits=20,decimal_places=2)
    percent = models.DecimalField(max_digits=10,decimal_places=10)
    before_tax = models.BooleanField()
    credit_debit = models.CharField(max_length=6, 
                                    choices=(('Debit','Income'),
                                             ('Credit','Expense'),))
    tax_category = models.ForeignKey(Tax_Category)
    account = models.ForeignKey(Account)
    active = models.BooleanField()
    deduct_taxes = models.BooleanField()

1 个答案:

答案 0 :(得分:2)

感谢大家的帮助,尤其谢谢。啤酒。试图在shell中打印表单并得到类型错误。

正在创建对象,但无法打印(或.as_p())。

问题出在Account模型中,Allocation and Deduction有一个外键:

class Account(models.Model):
    user = models.ForeignKey(User)
    account_type = models.ForeignKey(Account_Type)
    def __unicode__(self):
        return self.account_type

我删除了unicode方法并且工作正常。我猜unicode不会返回另一个模型的unicode方法,哈哈。