2010-02-16 36 views
8

我試圖找到一些關於如何在我自己的表單中使用ForeignKeyRawIdWidget的文檔。目前我不斷收到錯誤,「init()至少需要2個非關鍵字參數(1給出)」,它告訴我什麼都沒有。Django:在管理表單外使用ForeignKeyRawIdWidget

任何幫助將不勝感激。使用Google搜索可以發現很少但開放的對話,並且沒有任何可以找到如何實現它的例子。

更新:這已解決;見下面的解決方案

+0

您可以展示如何嘗試初始化小部件? – 2010-02-16 09:09:41

+0

如果您自行解決此問題,請將您的解決方案作爲答案發布並接受。在問題中包含解決方案令人困惑。 – Cerin 2013-09-06 15:56:13

+0

更好?感謝指針。 – tufelkinder 2013-09-06 19:41:52

回答

6

從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.remote_field自嘲field.rel。您可能想使用它(也適用於Django 1.11):

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

在Django 2.0'rel'已被棄用('RemovedInDjango20Warning:field.rel的用法已被棄用,改爲使用field.remote_field。)。您可能需要編輯答案以保持最新狀態。 – jorgeh 2017-12-27 20:03:44

0

這是從源代碼(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字段中設置。

+1

我也檢查了這個代碼...不完全是我期待的例子或文檔!當你什麼都沒有得到時,它很難排除故障。 – tufelkinder 2010-02-17 05:12:47