Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin: Change selected box of related fields to autocomplete

We have some models that are have a user as a foreign key. But with about 25000 users in our system, it's a bit daunting to find the one we need.

Is there a solution out there that's better than the select box? Maybe an autocomplete so we can start typing the user name / address? Or just a search box? When switching the related user for these objects, it's getting harder and harder with 25000 unsorted users.

Even just setting it to sort the users by username would be helpful.

like image 773
Brenden Avatar asked Mar 20 '12 19:03

Brenden


4 Answers

I had this problem and my conclusion was to use an autocomplete field instead. It works pretty well in most cases. The only problem is when you have a lot of entries that are mostly the same. For example, in your case, if you type Robert for the name and there's a few hundred Robert entries in the list...

UPDATE

As mentions in shuckc's answer, Django 2.0+ admin as now autocomplete built in.

For older Django or to use outside of the admin (old answer)

There are many apps that add autocomplete to the Django admin:

  • django-autocomplete-light
  • django-extensions (ForeignKeyAutocompleteAdmin)
  • django-autocomplete (on google code)
  • django-ajax-selects
  • django-admin-autocomplete
  • django-autocomplete (tyrion)

My preferred one is the last one. It's well written, it can be used with the admin and outside of the admin, it works with ManyToManyFields, ForeignKeyFields, CharFields, etc.

I did a fork of this project for my client that adds some niceties like a lookup (loupe) button like the ForeignKeyRawIdWidget.

like image 107
Etienne Avatar answered Nov 08 '22 03:11

Etienne


Django 2.0 admin has autocomplete built in, just set the autocomplete_fields field on the ModelAdmin class. e.g.

class QuestionAdmin(admin.ModelAdmin):
    ordering = ['date_created']
    search_fields = ['question_text']

class ChoiceAdmin(admin.ModelAdmin):
    autocomplete_fields = ['question']
like image 39
shuckc Avatar answered Nov 08 '22 02:11

shuckc


The simplest out-of-the-box solution is to add the field to your ModelAdmin's raw_id_fields -- then you'll get a pop-up window in which you can use the built-in searching/filtering and pagination control's to find and select the object you're after.

If you really want autocomplete, the other answers give a you reasonable starting point.

like image 6
DrMeers Avatar answered Nov 08 '22 01:11

DrMeers


You can use the ForeignKeyRawIdWidget from django.contrib.admin.widgets. It renders FK relations as an input with a small button along-side which presents a searchable pop up.

like image 4
Timmy O'Mahony Avatar answered Nov 08 '22 03:11

Timmy O'Mahony