Django: using ForeignKeyRawIdWidget outside of admin forms

后端 未结 2 1053
情话喂你
情话喂你 2020-12-09 20:55

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条回答
  • 2020-12-09 21:32

    This is from the source code (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)
    
        #.....
    

    From the remaining code, I would guess that rel is the foreign key field of your model. At one point, the code checks self.rel.limit_choices_to, and this attribute (limit_choices_to) can only be set on a ForgeinKey field.

    0 讨论(0)
  • 2020-12-09 21:37

    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),
    ...
    
    0 讨论(0)
提交回复
热议问题