raw_id_fields for modelforms

后端 未结 3 732
挽巷
挽巷 2021-01-01 22:52

I have a modelform which has one field that is a ForeignKey value to a model which as 40,000 rows. The default modelform tries to create a select box with 40,000 options, wh

3条回答
  •  北海茫月
    2021-01-01 23:20

    You can also use the entire raw_id_field admin widget, complete with the handy js popup search that the admin page has. You don't even need a model form. Here's how:

    import string
    from django.contrib.admin.widgets import ForeignKeyRawIdWidget
    from django import forms
    from models import MyModel
    
    # Have to subclass widget b/c 
    # django hardcodes a relative path to Admin Root URL: ../../..
    class HardcodedURLForeignKeyRawIdWidget(ForeignKeyRawIdWidget):
        def render(self, *args, **kwargs):
            original_render = super(HardcodedURLForeignKeyRawIdWidget, 
                self).render(*args, **kwargs)
            ADMIN_ROOT_URL = "/admin/"
            return string.replace(original_render,"../../../", ADMIN_ROOT_URL)
    
    
    class FieldLookupForm(forms.Form):
        my_foreignkey_field = forms.CharField(max_length=10,
            widget=HardcodedURLForeignKeyRawIdWidget(
                MyModel._meta.get_field("foreignkey_field").rel))
    

    Add the relevant admin js to your template, and viola

    {% block header %}
    
    
    
    
    
    
    
    {% endblock %}
    

提交回复
热议问题