Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: using ForeignKeyRawIdWidget outside of admin forms

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.

like image 661
tufelkinder Avatar asked Feb 16 '10 06:02

tufelkinder


1 Answers

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),
        }

Update

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),
...
like image 169
tufelkinder Avatar answered Sep 20 '22 09:09

tufelkinder