Django:在管理表单之外使用 ForeignKeyRawIdWidget [英] Django: using ForeignKeyRawIdWidget outside of admin forms

查看:27
本文介绍了Django:在管理表单之外使用 ForeignKeyRawIdWidget的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找一些有关如何在我自己的表单中使用 ForeignKeyRawIdWidget 的文档.目前我不断收到错误消息,init() 至少需要 2 个非关键字参数(1 个给定)",这并没有告诉我什么.

I'm trying to find some documentation of how to use the ForeignKeyRawIdWidget in my own forms. Currently I keep getting the error, "init() takes at least 2 non-keyword arguments (1 given)" which tells me nothing.

任何帮助将不胜感激.谷歌搜索这个结果很少,但只有开发对话,没有我能找到如何实现它的示例.

Any help would be most appreciated. Googling this turns up little but dev conversations and no examples that I can find of how to implement it.

更新:已解决;请参阅下面的解决方案.

Update: This is solved; see solution below.

推荐答案

从 Django 1.5 开始,这可以在非管理员表单中重用 ForeignKeyRawIdWidget.

As of the Django 1.5, this works to reuse the ForeignKeyRawIdWidget in non-admin forms.

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):

Django 2.0 is deprecating field.rel in favor of field.remote_field. You might want to use this instead (also works on Django 1.11):

...
ForeignKeyRawIdWidget(Invoice._meta.get_field('customer').remote_field, site),
...

这篇关于Django:在管理表单之外使用 ForeignKeyRawIdWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆