Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin: change select box for foreign key to search autocomplete, like search objects

The Django admin panel has a search autocomplete with search_fields on the list of objects of a model, but right now I have 3000 users. To add a user manually is dificult with the selectbox; I need the same behavior like the searchfields for selecting a user foreinkey User.

How can I include the Django search feature on the form for editing inside the admin panel?

from myapp.models import Red 
from django.contrib.auth.models import User

class Red(models.Model):
    customer = models.ForeignKey(User, verbose_name="Cliente")
    pub_date = models.DateTimeField(default=datetime.now, blank=True)
like image 905
Softsofter Avatar asked Apr 09 '15 17:04

Softsofter


2 Answers

Since Django 2.0, you can use autocomplete_fields to generate autocomplete fields for foreign keys.

class UserAdmin(admin.ModelAdmin):
    search_fields = ['username', 'email']

class RedAdmin(admin.ModelAdmin):
    autocomplete_fields = ['customer']
like image 72
Antoine Pinsard Avatar answered Nov 10 '22 00:11

Antoine Pinsard


Django has no built-in autocomplete functionality for foreign keys on admin but the raw_id_fields option may help:

class RedAdmin(admin.ModelAdmin):
    raw_id_fields = ("customer", )

If you want real autocomplete then you have to use 3rd-party app like django-autocomplete-light or some of the other solutions.

like image 10
catavaran Avatar answered Nov 10 '22 00:11

catavaran