我试图找到一些如何在我自己的表单中使用ForeignKeyRawIdWidget的文档。目前我一直收到错误,“init()至少需要2个非关键字参数(给定1个)”,这对我没有任何意义。
非常感激任何的帮助。谷歌搜索这个很少但是开发对话并没有我能找到如何实现它的例子。
更新:这已解决;见下面的解决方案
从Django 1.5开始,这可以在非管理表单中重用ForeignKeyRawIdWidget。
from django.contrib.admin.sites import site
class InvoiceForm(ModelForm):
class Meta:
model = Invoice
widgets = {
'customer': ForeignKeyRawIdWidget(Invoice._meta.get_field('customer').rel, site),
}
更新
Django 2.0正在弃用field.rel
,转而使用field.remote_field
。你可能想要使用它(也适用于Django 1.11):
...
ForeignKeyRawIdWidget(Invoice._meta.get_field('customer').remote_field, site),
...
这是源代码(django.contrib.admin.widgets
):
class ForeignKeyRawIdWidget(forms.TextInput):
"""
A Widget for displaying ForeignKeys in the "raw_id" interface rather than
in a <select> box.
"""
def __init__(self, rel, attrs=None):
self.rel = rel
super(ForeignKeyRawIdWidget, self).__init__(attrs)
#.....
从剩下的代码中,我猜想rel
是你模型的外键字段。有一次,代码检查self.rel.limit_choices_to
,这个属性(limit_choices_to
)只能在ForgeinKey
字段上设置。