我在models.py中的以下内容:
class Item(models.Model):
date = models.DateField(_('date'), blank=True, null=True)
description = models.CharField(_('description'), max_length=255)
content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
object_id = models.PositiveIntegerField(_('object id'), db_index=True)
object = generic.GenericForeignKey('content_type', 'object_id')
class ItemAccountAmountRef(Item):
""" Items of which a Quote or an Invoice exists. """
amount = models.DecimalField(max_digits=10, decimal_places=2)
reference = models.CharField(max_length=200)
debit_account = models.ForeignKey(Account, related_name='receivables_receipt_debit_account')
credit_account = models.ForeignKey(Account, related_name='receivables_receipt_credit_account')
class PaymentItem(ItemAccountAmountRef):
pass
class Payment(models.Model):
invoice = models.ManyToManyField(Invoice, null=True, blank=True)
date = models.DateField('date')
attachments = generic.GenericRelation(Attachment)
site = models.ForeignKey(Site, related_name='payment_site', null=True, blank=True
items = generic.GenericRelation(PaymentItem)
admin.py中的:
class PaymentItemInline(generic.GenericTabularInline):
model = PaymentItem
form = PaymentItemForm
class PaymentAdmin(admin.ModelAdmin):
inlines = [PaymentItemInline]
form.py中的:
class PaymentItemForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PaymentItemForm, self).__init__(*args, **kwargs)
self.fields['credit_account'].label = "Bank Account"
在PaymentItemInline中,标签没有变化。我尝试过更改其他属性,例如工作的班级。如果我在调试模式下运行init,我可以看到标签变量正在改变,但是在表单呈现时,该字段仍然标记为信用帐户。有什么建议吗?
答案 0 :(得分:2)
你有98%的路在那里。而不是尝试使用__init__
中的表单字段来替换,只需在ModelForm
中重新定义它。如果你把它命名为同样的东西,django将能够弄清楚它应该验证&保存到ForeignKey
字段。您可以使用相同的公式为ModelForm
中的给定字段完全更改字段或小部件。
您可以在此处找到每种模型字段类型的默认表单字段类型:https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types
class PaymentItemForm(forms.ModelForm):
credit_account = forms.ModelChoiceField(label="Bank Account", queryset=Account.objects.all())
就是这样。根本不需要覆盖任何功能:)
顺便提一下,此字段的文档位于:https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield