djangodjango-modelsdjango-formsdjango-admindjango-admin-actions

Replace foreign key dropdown with textbox with add/edit icon - Django


Related to foreign key fields in the Django Admin, the default display element is a drop down list box containing all of the foreign key items from the related model. I my app it will contain thousands of items and I am looking to change the admin interface and have it use a text box instead of the populated drop down.

Looking for textbox with add/edit icon next to it, so that we dont get populated values, we just directly add or edit.

Is there any way around to achieve it.


Solution

  • You can try use custom Form and realize custom Widget on this form field. (I use for this desicion 3rd party library django_select2)

    from django import forms
    from django_select2.forms import ModelSelect2Widget
    
    
    class KeyWidget(ModelSelect2Widget):
        model = ModelToKey
        search_fields = ['field__icontains']
    
        def label_from_instance(self, obj):
            return u'{}'.format(obj.field)
    
    
    class CustomForm(forms.ModelForm):
    
        class Meta:
            model = ModelWithKey
            fields = ('foreign_key_field')
            widgets = {
                'foreign_key_field': KeyWidget(attrs={'style': 'width:550px'}),
                }
    

    In also you can overload Form __init__ for customize queryset of objects for choosing in this field.