2

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.

Brijesh
  • 159
  • 1
  • 2
  • 10

2 Answers2

3

What you are looking for is raw_id_fields

class ArticleAdmin(admin.ModelAdmin):
    raw_id_fields = ("newspaper", )
  • By default, Django’s admin uses a select-box interface (<select>) for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.
  • raw_id_fields is a list of fields you would like to change into an Input widget for either a ForeignKey or ManyToManyField:

NOTE: The raw_id_fields Input widget should contain a primary key if the field is a ForeignKey or a comma separated list of values if the field is a ManyToManyField. The raw_id_fields widget shows a magnifying glass button next to the field which allows users to search for and select a value:

You can read the docs here

ajinzrathod
  • 925
  • 10
  • 28
0

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.

  • If `django_select2` is not part of the Django package, maybe you should precise which package to install and which are the requirements. – Olivier Pons Oct 02 '17 at 09:15